Forum: RSpec nil object error

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
76e01275c026bca5c46b2cb5e1ce174a?d=identicon&s=25 Mano ah (manoah)
on 2009-05-29 13:33
(Received via mailing list)
-- 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?
5d38ab152e1e3e219512a9859fcd93af?d=identicon&s=25 David Chelimsky (Guest)
on 2009-05-29 13:57
(Received via mailing list)
On Fri, May 29, 2009 at 6:26 AM, Diwakar, ANGLER - EIT
<diwakar@angleritech.com> 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
This topic is locked and can not be replied to.