Rails 4 – 未定义的方法’authenticate’为nil:NilClass
我正在开发一个使用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 '
这是我的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]
如果我要发布更多代码,请告诉我。
谢谢
我在文档中找到了答案:
如果您选择在routes.rb中进行身份validation,则会失去通过assert_routing测试路由的能力(它结合了assert_recognizes和assert_generates,因此您也会丢失它们)。 这是Rails的一个限制:Rack首先运行并检查您的路由信息,但由于function/控制器测试在控制器级别运行,您无法向Rack提供身份validation信息,这意味着request.env [‘warden’]为nil并且Devise生成其中一个以下错误:
NoMethodError: undefined method 'authenticate!' for nil:NilClass NoMethodError: undefined method 'authenticate?' for nil:NilClass
解决方案是在控制器测试中测试经过身份validation的路由。 为此,请为控制器测试存根您的身份validation方法。
如何存根validation。
- 将名称添加到Spree Devise注册
- Rails 4设计3.1.1 ActionController :: Devise中的UnknownFormat :: RegistrationsController #new
- 设计 – 如何更改设置,以便电子邮件地址不需要是唯一的
- 设计skip_confirmation! 不工作
- PhoneGap Mobile Rails身份validation(从头开始设计?身份validation?)
- 如何为控制器方法运行minitest?
- Rails 3设计了401个未经授权的ajax呼叫
- Rails 4 Devise重新激活“软删除”帐户
- 设备和ActiveResource