【问题标题】:Rails + rspec + devise = undefined method `authenticate_user!'Rails + rspec + devise = 未定义方法 `authenticate_user!'
【发布时间】:2012-01-11 12:34:50
【问题描述】:

应用控制器:

class ApplicationController < ActionController::Base
  before_filter :authenticate_user!

  protect_from_forgery
end

仪表板控制器:

class DashboardsController < ApplicationController
  def index
  end

end

DashboardsControllerSpec:

require 'spec_helper'
describe DashboardsController do
  include Devise::TestHelpers

  describe "GET 'index'" do
    it "returns http success" do
      get 'index'
      response.should be_success
    end
  end
end

结果:

Failure/Error: get 'index'
     NoMethodError:
       undefined method `authenticate_user!' for #<DashboardsController:0x007fef81f2efb8>

Rails 版本:3.1.3

Rspec 版本:2.8.0

设计版本:1.5.3

注意:我还创建了 support/deviser.rb 文件,但这无济于事。有什么想法吗?

【问题讨论】:

  • devise Wiki 提供了几种不同的方式将设计与 rspec 集成。

标签: ruby-on-rails rspec devise


【解决方案1】:
require 'spec_helper'
describe DashboardsController do
  before { controller.stub(:authenticate_user!).and_return true }
  describe "GET 'index'" do
    it "returns http success" do
      get 'index'
      response.should be_success
    end
  end
end

更新:

将上述语法与最新的 rspec 一起使用将给出以下警告

Using `stub` from rspec-mocks' old `:should` syntax without explicitly enabling the syntax is deprecated. Use the new `:expect` syntax or explicitly enable `:should` instead. Called from  `block (2 levels) in <top (required)>'.

使用这种新语法

  before do
     allow(controller).to receive(:authenticate_user!).and_return(true)
   end

【讨论】:

  • 我发现controller.stub(:authenticate_user!).and_return true 行很有帮助。但是,include Devise::TestHelpers 行是不必要且具有误导性的。这里没有使用来自Devise::TestHelpers 的任何方法,首先存根authenticate_user! 的一个原因是避免与Devise 的机器耦合。
  • @evanrmurphy 是的,你完全正确,不知道这包括在我的回答中做什么,我会删除它:)
  • 天啊,谢谢你。我尝试了一切,但没有任何效果。这是最简单、最快的解决方案!
【解决方案2】:

您的型号名称不是用户吗?如果是例如管理员,那么您需要将过滤器更改为:

before_filter :authenticate_admin!

这让我心疼了一阵子;我从 User 作为我的模型开始,后来决定将 Devise 添加到一个名为 Member 的模型中,但是我将原始的 :authenticate_user! 留在了我的控制器中,并且在运行 RSpec 时一直出现该错误。

【讨论】:

    【解决方案3】:

    看起来最好的方法是在你的 spec_helper.rb 文件中:

    RSpec.configure do |config|
      config.include Devise::TestHelpers, :type => :controller
    end
    

    有关详细信息,请参阅rspec wiki

    【讨论】:

      【解决方案4】:

      就我而言,我忘记了我在 routes.rb 文件中注释掉了 devise_for 行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-09
        相关资源
        最近更新 更多