Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


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

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

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

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

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