5

I have some Ruby code which looks like this:

Something.create do |x|
    x.foo = bar
end 

I'd like to write a test which uses a double in place of the block argument x, so that I can then call:

x_double.should_receive(:foo).with("whatever").

Is this possible?

stubotnik
  • 1,952
  • 2
  • 17
  • 31

1 Answers1

8
 specify 'something' do
   x = double
   x.should_receive(:foo=).with("whatever")
   Something.should_receive(:create).and_yield(x)
   # call the relevant method
 end
Mori
  • 27,279
  • 10
  • 68
  • 73
  • 3
    It's a good answer, but I'd like to nitpick. `Something.should_receive(:create)` is a test - an assertion - but it's not asserting the behaviour stubotnik said he wanted to test. So I'd differentiate test setup from the behaviour under test by using `Something.stub(:create).and_return(x)` which isn't asserting anything about the behaviour of `Something.create` – Mark Weston Jun 18 '13 at 12:47