2013-03-20 43 views
0

我正在爲項目的管理部分創建一個基礎控制器。所有控制器部分的whitin控制器都將繼承它。Rspec + Devise + BaseController

#app/controllers/admins/base_controller.rb 

class Admins::BaseController < ApplicationController 
    layout "admin_cms" 
    before_filter :authenticate_admin! 
end 

-

#spec/controllers/admins/base_controller_spec.rb 

require 'spec_helper' 

describe Admins::BaseController do 
    controller do 
    def index 
    end 
    end 

    describe "before_filter#authenticate_admin!" do 
    before(:each) do 
     @admin = FactoryGirl.create(:admin) 
     @request.env["devise.mapping"] = Devise.mappings[:admin] 
    end 

    context "when admin is not logged in" do 
     it "redirect admin to sign_in path" do 
     get :index 
     response.should redirect_to new_admin_session_path 
     end 
    end 

    end 
end 

我已經inclueded我spec_helper.rb設計:: TestHelpers並運行該規範時,我得到這個錯誤:

Admins::BaseController 
    before_filter#authenticate_admin! 
    when admin is not logged in 
     redirect admin to sign_in path (FAILED - 1) 

Failures: 

    1) Admins::BaseController before_filter#authenticate_admin! when admin is not logged  in redirect admin to sign_in path 
    Failure/Error: get :index 
    ActionView::MissingTemplate: 
     Missing template anonymous/index, application/index with {:locale=>[:en],  :formats=>[:html], :handlers=>[:erb, :builder, :coffee]}. Searched in: 
     * "#<RSpec::Rails::ViewRendering::EmptyTemplatePathSetDecorator:0xbaf75d4>" 
    # ./spec/controllers/admins/base_controller_spec.rb:17:in `block (4 levels) in <top (required)>' 

Finished in 0.17124 seconds 
1 example, 1 failure 

Failed examples: 

rspec ./spec/controllers/admins/base_controller_spec.rb:16 # Admins::BaseController before_filter#authenticate_admin! when admin is not logged in redirect admin to sign_in path 

我改變我的規格如下:

require 'spec_helper' 

describe Admins::BaseController do 
    controller do 
    def index 
     render nothing: true 
    end 
    end 

    describe "before_filter#authenticate_admin!" do 
    context "when admin is not logged in" do 
     it "redirect admin to sign_in path" do 
     get :index 
     response.should redirect_to new_admin_session_path 
     end 
    end 

    end 
end 

現在我得到這個錯誤:

Failures: 

    1) Admins::BaseController before_filter#authenticate_admin! when admin is not logged in redirect admin to sign_in path 
    Failure/Error: response.should redirect_to new_admin_session_path 
     Expected response to be a <:redirect>, but was <200> 

所以,由於某種原因它不進入authenticate_admin!過濾前。我有點迷路。再次感謝。

我使用Rails 3.2.13,Ruby 2.0.0,Rspec-rails 2.13.0和Devise 2.2.3。如果有人能幫助我解決這個問題,我真的很喜歡。提前致謝。

回答

3

好吧,3個小時後,我發現問題在於定義匿名控制器。

代替:

controller do 
    def index 
    end 
end 

我用:

controller(Admins::Base) do 
    def index 
    end 
end 

你需要,除非是ApplicationController中你想測試一個指定永遠是你正在測試的匿名控制器。

相關問題