2014-06-20 78 views
0

我曾經環顧四周,但也許我沒有在正確的位置尋找。我試圖找出如何測試一個用戶不能訪問一個頁面衛生組織控制器具有測試未經身份驗證的用戶Rspec/Devise

before_filter :authenticate_user! 

理想我想在同一時間捕捉色器件消息

"you need to sign in or sign up before continuing" 

我有這如此遠

require 'spec_helper' 

describe CampaignsController do 

    it "should not allow a user be able to access without being authenticated" do 
    get :index 
    response.should redirect_to(new_user_session_path) 
    end 

目前我得到的錯誤

Failure/Error: response.should redirect_to(new_user_session_path) 
Expected response to be a <redirect>, but was <200> 

廣告活動控制器

class CampaignsController < ApplicationController 
    before_filter :authenticate_user! 

def index 
    @campaigns = Campaign.all 
end 
end 

在我的天賦幫助我打電話以下

# Include Devise Test Helpers 
config.include Devise::TestHelpers, :type => :controller 
config.extend ControllerMacros, :type => :controller 

controller_macros.rb

module ControllerMacros 

def login_user 
    before(:each) do 
    @request.env["devise.mapping"] = Devise.mappings[:user] 
    user = FactoryGirl.create(:user) 
    sign_in user 
    end 
end 
end 

我不是在調用這個方法login_user階段,所以將spec_hel每通電話這個?

怎樣運用這個正確

任何幫助表示讚賞

感謝

+0

請發表'CampaignsController'。 –

+0

似乎對我來說,你能確定你沒有在某處(你在spec_helper中)調用'sign_in'方法嗎?我們是否也可以擁有ApplicationController的代碼? – ccyrille

+0

更新,現在思考你的意見後,你可以在 – Richlewis

回答

2

起初看起來似乎沒問題。如果您運行整個套件,則可能會導致問題,並且根據您撥打login_user的地點,它可能會將before(:each)添加到全部測試中。

我知道你想最小化打字,但通常我更喜歡我的測試更明確一點:我想看看規範中發生了什麼。

因此,如何我一般寫這種測試:

describe HomeController do 
    include Devise::TestHelpers 

    context "when not signed in" do 
    describe "GET 'index'" do 
     it "redirects to sign in" do 
     get 'index' 
     response.should be_redirect 
     end 
    end 
    describe "GET 'about'" do 
     it "returns http success" do 
     get 'about' 
     response.should be_redirect 
     end 
    end 
    end 

    context "when signed in" do 
    before do 
     user = FactoryGirl.create(:user) 
     sign_in(user) 
    end 
    describe 'GET :index' do 
     it "returns http success" do 
     get 'index' 
     response.should be_success 
     end 
    end 
    describe "GET 'about'" do 
     it "returns http success" do 
     get 'about' 
     response.should be_success 
     end 
    end 
    end 
end 

是,承認:我還是喜歡(使用should)老rspec的語法,它讀取更自然的我。

+0

謝謝你,這是一種更好的做事方式,我同意你對可讀性的看法,它更有意義,只需要幫助你想要的部分,就不會冒任何其他測試受到影響的風險。 .. – Richlewis

0

請嘗試

module ControllerMacros 

    def login_user 
    @request.env["devise.mapping"] = Devise.mappings[:user] 
    user = FactoryGirl.create(:user) 
    sign_in user 
    end 
end 

在rspec的文件

require 'spec_helper' 

describe CampaignsController do 

    it 'for authenticate user' do 
    before do 
     login user 
    end 
    end 

    it "should not allow a user be able to access without being authenticated" do 
    get :index 
    expect(response).to redirect_to(new_user_session_path) 
    end 
+0

恐怕同樣的反應,不工作 – Richlewis

+0

你有沒有得到上述代碼相同的錯誤? – Sanket

+0

是的,我沒有害怕 – Richlewis

相關問題