Nil object error

– Controller ----

def create

@avatars = Avatar.find( :all,
:conditions => { :user_id => 0 }
)

@avatars.concat( user.avatars )

end

— spec —

describe UserAvatarsController do

describe :create do

before(:each) do

@avatar = mock_model(Avatar)
@user = mock_model(User)
controller.stub!(:requires_user).and_return(@user)
Avatar.stub!(:find).and_return(@avatar)
User.stub(:avatar).and_return(@user)
Avatar.stub!(:concat).and_return(@user)

end

it “should create a new user avatar” do
Avatar.should_receive(:find).and_return(@avatar)
User.should_receive(:avatar).and_return(@user)
post :create
end
end

end

I am getting the below error

— Error —

You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.avatars

How should I spec this?

On Fri, May 29, 2009 at 6:26 AM, Diwakar, ANGLER - EIT
[email protected] wrote:

end
@avatar = mock_model(Avatar)
User.should_receive(:avatar).and_return(@user)
You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.avatars

How should I spec this?

What is the behaviour you’re trying to specify here? The docstring
says “it should create a user avatar,” but the example code expects
find on the Avatar class and avatar on the User class. And I can’t
tell how the create() code is actually creating anything.

That aside, the nil error is happening because the user() method is
returning nil (in user.avatars). You can fix that by changing this:

controller.stub!(:requires_user).and_return(@user)

to this:

controller.stub!(:user).and_return(@user)

Though you may need to also stub requires_user if it’s in a before
filter (which I think I remember from another thread on this), so
you’d actually want:

controller.stub!(:requires_user)
controller.stub!(:user).and_return(@user)

This way requires_user() doesn’t do anything, and the user() method
returns the mock user. Of course, it’s going to need to respond to the
avatars() method:

@user.stub!(:avatars).and_return([@avatar])

or something like that.

HTH,
David