Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

NoMethodError: undefined method `state' for nil:NilClass

I'm following the accepting friendships tutorial in the setting up the state machine stage and ran into an error:

1) Error:
UserFriendshipsControllerTest#test: #accept should update the state to accepted. :
NoMethodError: undefined method `state' for nil:NilClass
test/controllers/user_friendships_controller_test.rb:190:in `block (2 levels) in
<class:UserFriendshipsControllerTest>'

The error should be that the state is pending rather than accepted, but instead it is saying that the state method is undefined. Here is the test that started causing the issue:

should "update the state to accepted" do
    assert_equal 'accepted', @user_friendship.state
end

I did get a deprecation warning on conditions in my user model previously and updated it to a scope block, and thought that may have been the issue. However, when I changed it back to conditions I still receive the same error.

Here are the relationships in my user model in case this helps:

has_many :statuses
has_many :user_friendships
has_many :friends, through: :user_friendships, 
                 conditions: { user_friendships: { state: 'accepted' } }

has_many :pending_user_friendships, class_name: 'UserFriendship', 
                                                             foreign_key: :user_id, 
                                                             conditions: { state: 'pending' }

has_many :pending_friends, through: :pending_user_friendships, source: :friend

Any ideas/suggestions? Thanks in advance!

1 Answer

Figured it out!! It was a typo on my part... Basically my end tag for the context that included "update state to accepted" test was in the wrong place. Here is the updated version that works now:

context "when logged in" do
  setup do
    @user_friendship = create(:pending_user_friendship, user: users(:jake))
    sign_in users(:jake)
    put :accept, id: @user_friendship
    @user_friendship.reload
  end

  should "assign a user friendship" do
    assert assigns(:user_friendship)
    assert_equal @user_friendship, assigns(:user_friendship)
  end

  should "update the state to accepted" do
    assert_equal 'accepted', @user_friendship.state
  end

end