[rspec-users] set expectation using self in constructor?

Chuck Remes cremes.devlist at mac.com
Thu Jul 15 09:55:27 EDT 2010


On Jul 14, 2010, at 4:20 PM, Matt Wynne wrote:

> 
> You can do this, by using a test spy to remember the value of foo passed into the stubbed constructor and then later comparing it:
> 
> let(:foo) { Foo.new }
> 
> it "should allocate a helper class Foo" do
>  actual_foo = Bar.should_receive(:new) do |the_foo|
>    the_foo
>  end
>  actual_foo.should == foo
> end
> 
> Whether you want to do this though, is another question. I think it's a bit of an anti-pattern personally. I'd probably let acceptance tests catch mistakes in this kind of thing, and concentrate on speccing the interaction between Foo and Bar once you've got the instances spun up.

For those following along at home, this exact technique did not work. The +actual_foo+ variable was holding some mock value instead of the real self value.

I fixed it by assigning to a variable inside the block that had been defined outside the block (avoiding block scope issues).

let(:foo) { Foo.new }

it "should allocate a helper class Foo" do
  actual_foo = nil
  Bar.should_receive(:new) do |the_foo|
    actual_foo = the_foo
  end

  actual_foo.should == foo
end

This succeeds.

Thanks to all for your help.

cr



More information about the rspec-users mailing list