Search code examples
ruby-on-railstestingfunctional-testingfixtures

Rails 4: Error on collection through association in (TestCase) controller index action test


polls_controller.rb

  def index
    @polls = current_user.polls
  end

Above works fine for my user (current_user) has_many polls association. I thought I could replicate this in tests by setting appropriate fixtures.

polls_controller_test.rb

  setup do
    @current_user = users(:bob)
    @poll = @current_user.polls.build(title: "Poll")
  end

  test "should get index" do
    @polls = @current_user.polls
    get :index
    assert_response :success
    assert_not_nil assigns(:polls)
  end

polls.yml

one:
  title: Poll-1
  user: bob

two:
  title: Poll-2
  user: bob

users.yml

bob:
  name: Bob Example
  email: [email protected]
  password_digest: <%= User.digest('password') %>

However, running the test returns

NoMethodError: undefined method `polls' for nil:NilClass

Can I not do this? (Apparently not this way.) Why is @current_user nil?


Solution

  • Ok, figured it out. As always, was not due to some esoteric bug or syntax requirement, but rather that I did not specify session[:user_id] = @current_user.id in the test setup, which is referenced by my current_user helper method. Therefore, test framework was seeing current_user as nil. Cheers.