如何在ruby / rspec中模拟/存档File.open each_line

时间:2016-03-02 20:11:30

标签: ruby rspec

如何模拟/存储这个以便我可以测试each_line中发生了什么?

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

1 个答案:

答案 0 :(得分:2)

尝试这样的事情:

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