如何模拟/stub文件。在ruby/rspec中打开每一行

如何模拟/stub文件。在ruby/rspec中打开每一行,ruby,rspec,Ruby,Rspec,如何对其进行模拟/存根,以便我可以测试每行中发生的事情 File.open(file_path) do |file| file.each_line do |line| #do something here end end 试着这样做: RSpec.describe "an example of mock" do let(:content) { StringIO.new("1\n2\n3") } specify do allow(File).to receiv

如何对其进行模拟/存根,以便我可以测试每行中发生的事情

File.open(file_path) do |file|
  file.each_line do |line|
    #do something here
  end 
end

试着这样做:

RSpec.describe "an example of mock" do
  let(:content) { StringIO.new("1\n2\n3") }

  specify do
    allow(File).to receive(:open).and_yield(content)
    # do whatever you want
  end
end

你在每一行里面到底在做什么。。。你能测试一下吗?我可以,但我更愿意找到一个更好的解决方案并进行更彻底的测试。我认为你在测试最终结果时正在测试实现细节……试了一下,我得到了以下结果:
Failure/Error:descripted_class.new.process_文件(“test”)要求生成|[#]|但是没有传递任何块
将“expect”更改为“allow”(参见更新的示例)。但是生产代码似乎没有在
文件上提供块。open
刚刚测试了下一个代码
ruby RSpec.description“一个模拟的例子”do-let(:content){StringIO.new(“1\n2\n3”)}指定do-allow(File)。to-receive(:open)。and_-yield(content)File.open('foo'){f | put f.read}end