NoMethodError:nil的未定义方法`email':NilClass

时间:2015-07-01 16:47:37

标签: ruby-on-rails-4 integration-testing railstutorial.org minitest

还有一些其他线程可以解决这个问题,但没有一个能帮我们解决问题。

当我们使用Minitest运行其中一个集成测试时,我们得到以下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>'

以下是我们的test_helper.rb文件:

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

这是我们users_index_test.rb文件的第一部分:

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

我们知道为什么会出现这个NoMethodError: undefined method 'email' for nil:NilClass错误以及如何修复它?

1 个答案:

答案 0 :(得分:1)

这是因为@user未在您的设置方法中初始化。您初始化@admin@non_admin,但不是@user