How to test a function which takes a block with rspec

constantine1 picture constantine1 · Feb 19, 2013 · Viewed 10.1k times · Source

I have a function, which accepts a block, opens a file, yields and returns:

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

I am trying to write a test for it using rspec. How do I stub File.open so that it passed an object f (supplied by me) to the block instead of trying to open an actual file? Something like:

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

Answer

Amir picture Amir · Feb 19, 2013

I think what you're looking for are yield matchers, i.e:

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