Thibaud Clement
Thibaud Clement

Reputation: 6897

NoMethodError: undefined method `email' for nil:NilClass

There are some other threads tackling this issue, but none of them helped us fix our problem.

When we run one of our integration tests with Minitest, we get the following ERROR:

ERROR["test_index_including_pagination", UsersIndexTest, 2015-06-30 06:44:19 -0700]
 test_index_including_pagination#UsersIndexTest (1435671859.78s)
NoMethodError:         NoMethodError: undefined method `email' for nil:NilClass
            test/test_helper.rb:20:in `log_in_as'
            test/integration/users_index_test.rb:11:in `block in <class:UsersIndexTest>'
        test/test_helper.rb:20:in `log_in_as'
        test/integration/users_index_test.rb:11:in `block in <class:UsersIndexTest>'

Here is our test_helper.rb file:

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require "minitest/reporters"
Minitest::Reporters.use!

class ActiveSupport::TestCase
  fixtures :all

  # Returns true if a test user is logged in.
  def is_logged_in?
    !session[:user_id].nil?
  end

  # Logs in a test user.
  def log_in_as(user, options = {})
    password    = options[:password]    || 'password'
    remember_me = options[:remember_me] || '1'
    if integration_test?
      post login_path, session: { email:       user.email,
                                  password:    password,
                                  remember_me: remember_me }
    else
      session[:user_id] = user.id
    end
  end

  private

    # Returns true inside an integration test.
    def integration_test?
      defined?(post_via_redirect)
    end
end

And here is the first part of our users_index_test.rb file:

require 'test_helper'

class UsersIndexTest < ActionDispatch::IntegrationTest

  def setup
    @admin     = users(:michael)
    @non_admin = users(:archer)
  end

  test "index including pagination" do
    log_in_as(@user)
    get users_path
    assert_template 'users/index'
    assert_select 'div.pagination'
    User.paginate(page: 1).each do |user|
      assert_select 'a[href=?]', user_path(user), text: user.first_name + " " + user.first_name
    end
  end

Any idea why we get this NoMethodError: undefined method 'email' for nil:NilClass error and how to fix it?

Upvotes: 0

Views: 1167

Answers (1)

blowmage
blowmage

Reputation: 8984

This is because @user was not initialized in your setup method. You initialize @admin and @non_admin, but not @user.

Upvotes: 2

Related Questions