[rspec-users] and_return question

David Chelimsky dchelimsky at gmail.com
Thu May 6 22:51:03 EDT 2010

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?

More information about the rspec-users mailing list