Rails 4-未定义的方法'authenticate'为nil:NilClass

myc*_*ius 2 ruby ruby-on-rails shoulda devise

我正在使用Rails 4&Devise构建社交网络的课程。

我被困试图通过一门课程,这是我得到的错误:

1) Error:
UserFriendshipsControllerTest#test_: #new when not logged in should get redirected to the login page. :
NoMethodError: undefined method `authenticate!' for nil:NilClass
    test/controllers/user_friendships_controller_test.rb:8:in `block (3 levels) in <class:UserFriendshipsControllerTest>'
Run Code Online (Sandbox Code Playgroud)

这是我的users_friendships_controller_test.rb:

require 'test_helper'

class UserFriendshipsControllerTest < ActionController::TestCase

context "#new" do
    context "when not logged in" do
        should "get redirected to the login page" do
            get :new
            assert_response :redirect
      end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我的user_friendship.rb:

class UserFriendship < ActiveRecord::Base
    belongs_to :user
    belongs_to :friend, class_name: "User", foreign_key: "friend_id"

    private

        def friendship_params
            params.require(:user).permit(:user_id, :friend_id, :friend)
        end
end
Run Code Online (Sandbox Code Playgroud)

我添加到user_friendships_controller.rb的唯一方法是空白的新方法,并且:

before_filter :authenticate_user!, only: [:new]
Run Code Online (Sandbox Code Playgroud)

请让我知道是否应该发布更多代码。

谢谢

Far*_*lko 5

我在文档中找到了答案:

如果选择在route.rb中进行身份验证,则将失去通过assert_routing(结合assert_recognizes和assert_generates,因此也会丢失它们)来测试路由的能力。这是Rails中的一个局限性:Rack首先运行并检查您的路由信息​​,但是由于功能/控制器测试在控制器级别运行,因此您无法向Rack提供身份验证信息,这意味着request.env ['warden']为nil,而Devise会生成其中一个以下错误:

NoMethodError: undefined method 'authenticate!' for nil:NilClass
NoMethodError: undefined method 'authenticate?' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)

解决方案是在控制器测试中测试经过身份验证的路由。为此,请将您的身份验证方法存入控制器测试中。

如何存根身份验证。