ruby-on-rails “未定义方法`admin?' for nil:NilClass”在Ruby on rails中测试未登录用户时

6za6bjd0  于 2023-06-25  发布在  Ruby
关注(0)|答案(1)|浏览(134)

我正在阅读《Ruby on Rails教程:Learn Web Development with Rails 7th edition”,在第10章中,我们写了一个测试来检查如果用户试图删除一个用户,当用户没有以管理员身份登录时,是否会被重定向到登录页面:

test 'should redirect destroy when not logged in' do
    assert_no_difference 'User.count' do
      delete user_path(@user)
    end
    assert_response :see_other
    assert_redirected_to login_url
  end

但我在控制台上得到了这个错误:

ERROR UsersControllerTest#test_should_redirect_destroy_when_not_logged_in (4.09s)
Minitest::UnexpectedError:         NoMethodError: undefined method `admin?' for nil:NilClass
            app/controllers/users_controller.rb:77:in `admin_user'
            test/controllers/users_controller_test.rb:61:in `block (2 levels) in <class:UsersControllerTest>'
            test/controllers/users_controller_test.rb:60:in `block in <class:UsersControllerTest>'

如果我修改这个代码:

def admin_user
      redirect_to(root_url, status: :see_other) unless current_user.admin?
    end

致:

def admin_user
      redirect_to(root_url, status: :see_other) unless current_user.present? && current_user.admin?
    end

正如在另一篇文章中所建议的那样,然后我得到了这个错误:

FAIL UsersControllerTest#test_should_redirect_destroy_when_not_logged_in (3.62s)
        Expected response to be a redirect to <http://www.example.com/login> but was a redirect to <http://www.example.com/>.
        Expected "http://www.example.com/login" to be === "http://www.example.com/".
        test/controllers/users_controller_test.rb:65:in `block in <class:UsersControllerTest>'
guykilcj

guykilcj1#

如果您在控制器中有这样的代码

redirect_to(root_url, status: :see_other) unless current_user.admin?

如果您尝试在当前用户为nil(非身份验证用户)时调用此方法,NoMethodError将引发
要修复它,请使用安全导航语法

redirect_to(root_url, status: :see_other) unless current_user&.admin?

接下来,你需要决定你将重定向到哪里:到根页面或登录页面。相应的测试将如下所示

# controller
redirect_to(root_url, status: :see_other) unless current_user&.admin?
# test
assert_redirected_to root_url

# controller
redirect_to(login_url, status: :see_other) unless current_user&.admin?
# test
assert_redirected_to login_url

相关问题