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

Matt Wynne matt at mattwynne.net
Fri Jul 16 05:29:52 EDT 2010


On 15 Jul 2010, at 14:55, Chuck Remes wrote:

> 
> 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.

Sorry. Do we think this is a bug in rspec? I'd have expected the block to return the last evaluated value. But is that just me?

> 
> 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
> 
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users

cheers,
Matt

http://blog.mattwynne.net
+44(0)7974 430184



More information about the rspec-users mailing list