Rails中的NoMethodError错误

时间:2016-12-13 02:10:36

标签: ruby-on-rails ruby nomethoderror

我正在阅读迈克尔·哈特尔的Ruby教程,并且在测试失败的情况下被困了一天

我跑步时得到这个:

Error:
UsersControllerTest#test_should_redirect_edit_when_logged_in_as_wrong_user:
NoMethodError: undefined method `session' for nil:NilClass
test/test_helper.rb:19:in `log_in_as'
test/controllers/users_controller_test.rb:37:in `block in <class:UsersControllerTest>'

这是调用代码:

require 'test_helper'

class UsersControllerTest < ActionDispatch::IntegrationTest

  def setup
    @user        = users(:michael)
    @otheruser   = users(:archer)
  end

test "should redirect update when logged in as wrong user" do
    log_in_as(@other_user)
    patch user_path(@user), params: { user: { name: @user.name,
                                              email: @user.email } }
    assert flash.empty?
    assert_redirected_to root_url
  end


*And here is the method I'm trying to call from the **test_helper** class:*

# Log in as a particular user
  def log_in_as(user)
    session[:user_id] = user.id
  end

2 个答案:

答案 0 :(得分:1)

我在 test_helper.rb 课程中错过了一部分:

class ActionDispatch::IntegrationTest

  # Log in as a particular user.
  def log_in_as(user, password: 'password', remember_me: '1')
    post login_path, params: { session: { email: user.email,
                                          password: password,
                                          remember_me: remember_me } }
  end
end

感谢您一起来看看!

答案 1 :(得分:0)

您是否在 application_controller.rb 中添加了这行代码:include SessionsHelper

您在上述代码中的设置方法中输入了拼写错误:@otheruser = users(:archer)应为@other_user = users(:archer)

再次检查测试文件中的代码: test / controllers / users_controller_test.rb

特别是代码的这一部分:

 test "should redirect edit when logged in as wrong user" do
    log_in_as(@other_user)
    get edit_user_path(@user)
    assert flash.empty?
    assert_redirected_to root_url
  end

希望它有所帮助!