2012-01-11 80 views
8

ApplicationController中:Rails + rspec + devise =未定義的方法`authenticate_user!'

class ApplicationController < ActionController::Base 
    before_filter :authenticate_user! 

    protect_from_forgery 
end 

DashboardsController:

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

注:我還創建支持/ deviser.rb文件,但沒有幫助。有任何想法嗎?

+1

的[設計維基](https://github.com/plataformatec/devise/wiki/How-To:-Controllers-and-Views-tests-with-Rails-3-(和-rspec的))提供了一種幾種不同的方式來整合設計與rspec。 – 2012-01-11 12:40:45

回答

12
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 
+0

我發現'controller.stub(:authenticate_user!)。和_return true'行非常有幫助。然而,'包括Devise :: TestHelpers'這一行是不必要的和誤導的。這裏沒有使用'Devise :: TestHelpers'的方法,首先存放'authenticate_user!'的一個原因是爲了避免與Devise的機器耦合。 – evanrmurphy 2012-03-15 19:52:15

+1

@evanrmurphy葉氏,你是正確的compeltely,不知道這是什麼包括我的回答做,我會刪除它:) – 2012-03-16 07:52:15

7

比其他型號名稱的東西用戶?如果它是例如管理員,那麼你需要改變你的過濾器:

before_filter :authenticate_admin! 

這讓我有一段時間;我以User作爲我的模型開始,後來決定將Devise添加到名爲Member的模型中,但我將原始的:authenticate_user!保留在我的控制器中,並在運行RSpec時不斷得到該錯誤。

+0

謝謝謝謝謝謝! – 2014-03-03 18:26:58

3

貌似要做到這一點的最好辦法是在你的spec_helper.rb文件中的以下內容:

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

有關詳細信息,請參閱rspec wiki

1

在我的情況下,我忘記了我在我的routes.rb文件中註釋掉了devise_for行。

相關問題