【问题标题】:Rails 4 - undefined method 'authenticate' for nil:NilClassRails 4 - nil:NilClass的未定义方法'authenticate'
【发布时间】:2016-07-05 21:42:59
【问题描述】:

我正在学习使用 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>'

这是我的 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

我的 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

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

before_filter :authenticate_user!, only: [:new]

如果我应该发布更多代码,请告诉我。

谢谢

【问题讨论】:

  • 你能提供user_friendships_controller列表
  • @farhatmihalko class UserFriendshipsController &lt; ApplicationController before_filter :authenticate_user!, only: [:new] def new end end

标签: ruby-on-rails ruby devise shoulda


【解决方案1】:

我在documentation找到答案:

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

NoMethodError: undefined method 'authenticate!' for nil:NilClass
NoMethodError: undefined method 'authenticate?' for nil:NilClass

解决方案是在控制器测试中测试经过身份验证的路由。到 执行此操作,为控制器测试存根您的身份验证方法。

How to stub authentication.

【讨论】:

    猜你喜欢
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多