14

我有一个函数,它接受一个块,打开一个文件,产生并返回:

def start &block
    .....do some stuff
    File.open("filename", "w") do |f|
        f.write("something")
        ....do some more stuff
        yield
    end
end

我正在尝试使用 rspec 为它编写一个测试。如何存根 File.open 以便将对象 f (由我提供)传递给块,而不是尝试打开实际文件?就像是:

it "should test something" do
    myobject = double("File", {'write' => true})
    File.should_receive(:open).with(&blk) do |myobject|
        f.should_receive(:write)
        blk.should_receive(:yield) (or somethig like that)
    end
end
4

2 回答 2

5

我认为您正在寻找的是yield matchers,即:

it "should test something" do
  # just an example
  expect { |b| my_object.start(&b) }.to yield_with_no_args
end
于 2013-02-19T11:07:52.567 回答
1

您的另一个选择是使用 File 的新对象来存根 :open,如下所示:

file = File.new
allow(File).to receive(:open) { file }
file.each { |section| expect(section).to receive(:write) }
# run your method
于 2015-01-27T14:06:08.640 回答