[rspec-users] and_return question

Phillip Koebbe phillipkoebbe at gmail.com
Fri May 7 07:10:53 EDT 2010


  On 2010-05-06 9:51 PM, David Chelimsky wrote:
> On May 6, 2010, at 10:09 AM, Phillip Koebbe wrote:
>
>> Are these two forms theoretically functionally equivalent:
>>
>> 1)
>>
>> car = stub_model(Car)
>> Car.stub(:new).and_return(car)
>>
>> 2)
>>
>> Car.stub(:new).and_return(stub_model(Car))
>>
>> I ask because I thought they were, but just hit something that suggests they are not. I was originally using the first form, but then thought I'd shorten it up a little (especially since nothing special is happening in the stub_model call), so I changed it to form 2. But when I did, I got an error:
>>
>> NoMethodError in 'Web::Agent::NelliesController get :new should assign to @nelly'
>> You have a nil object when you didn't expect it!
>> You might have expected an instance of ActiveRecord::Base.
>> The error occurred while evaluating nil.id=
>> /Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/object/misc.rb:39:in `returning'
>> ./spec/controllers/web/agent/nellies_controller_spec.rb:140:
>> script/spec:10:
>>
>> Line 140 of the spec was where I was using form 2. I change it back to form 1 and the error went away.
>>
>> Thoughts?
> stub_model(Car) invokes Car.new. The call to Car.stub(:new) overrides new() before stub_model(Car) is evaluated. Make sense?

Thank, David!

Yes, it makes perfect sense. I have use form 2 a few times before 
without any difficulty, and hadn't really thought about it. In this 
particular case, though, I was doing something just slightly different 
that happened to expose this very important detail.

Peace,
Phillip



More information about the rspec-users mailing list