如何使用rspec测试一个带块的函数

时间:2013-02-19 10:45:44

标签: ruby rspec mocking rspec2 stubbing

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

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

2 个答案:

答案 0 :(得分:3)

我认为你所寻找的是yield matchers,即:

it "should test something" do
  # just an example
  expect { |b| my_object.start(&b) }.to yield_with_no_args
end

答案 1 :(得分:1)

你的另一个选择是存根:用File的新对象打开,如下:

file = File.new
allow(File).to receive(:open) { file }
file.each { |section| expect(section).to receive(:write) }
# run your method