2015-11-28 107 views
1

我正在使用Devise進行用戶登錄和用於測試的東西和rspec。我已經查看了rspec的Devise測試指南,並將ControllerMicros與控制器規格混合使用。 而實際上的東西都工作正常,如果我有這樣的組織測試:rspec +設計:current_user在測試中爲零

describe 'GET #index' do 
    context 'user logged in but not admin' do 
     login_user 
     it 'should redirect to root_path for non_user' do 
     get :index 
     // I have asserted that the current_user here is not nil 
     expect(response).to redirect_to(root_path) 
     end 
    end 
    end 

但是,如果我在第2周的測試,我得到了CURRENT_USER是對非第一個測試爲零。

describe 'GET #index' do 
    context 'user logged in but not admin' do 
     login_user 
     it 'should redirect to root_path for non_user' do 
     get :index 
     // I have asserted that the current_user here is not nil 
     expect(response).to redirect_to(root_path) 
     end 

     it 'should do some other thing' do 
     get :index 
     // the current_user method returns nil here 
     expect(response).to redirect_to(root_path) 
     end 
    end 
    end 

而最糟糕的是,它似乎這個問題不確定性:發生有些隨意 - 經過多次失敗的運行剛剛通過我的電腦上的套裝原因(但仍無法對特拉維斯my build

一些額外的信息:

的ControllerMacro.rb

module ControllerMacros 
    def login_admin 
    before(:each) do 
     # @request.env["devise.mapping"] = Devise.mappings[:user] 
     user = User.find_by(email: '[email protected]') 
     user ||= FactoryGirl.create(:user, email: '[email protected]', uid: 'default_admin.controller.spec') 
     admin = Admin.find_by(user_id: user.id) 
     FactoryGirl.create(:admin, user: user) if not admin 
     sign_in user 
    end 
    end 

    def login_user(user = nil) 
    before(:each) do 
     # @request.env["devise.mapping"] = Devise.mappings[:user] 
     user ||= User.find_by(email: '[email protected]') 
     user ||= FactoryGirl.create(:user, email: '[email protected]', uid: 'default_user.controller.spec') 
     sign_in user 
    end 
    end 
end 

的rails_helper.rb

01每塊每進行一次測試運行它:當測試套件負荷,你應該把它放在一個前
RSpec.configure do |config| 
    # for loading devise in test 
    config.include Devise::TestHelpers, :type => :controller 
    config.extend ControllerMacros, :type => :controller 
end 

回答

1

login_user方法運行。

describe "GET index" do 
    before do 
    login_user 
    end 
    it 'blabla' do 
    get :index 
    expect(response).to redirect_to(root_path) 
    end 
end 

PS:不知道你在login_user方法做什麼,而是設計有一些很不錯的幫手,你可以包括從評論

遵循

#rails_helper.rb 
RSpec.configure do |config| 
    config.include Devise::TestHelpers, type: :controller 
end 

#then in you test 
before do 
    sign_in user_instance 
end 

UPDATE如果您有多種類型的用戶/設計登錄條目,可能會嘗試指定您嘗試登錄用戶的設計映射,如下所示:

sign_in :user, user_instance 
sign_in :admin, admin_user_instance  
+0

我已經在微指令之前(每個)指定了。這不是訣竅嗎? –

+0

應該像你一樣炒作,更新我的答案也許試試我提供的alt語法。如果你想要我的看法,但是你的ControllerMacro方法做了太多的事情,你可以設想讓用戶在不同的「上下文」塊中嵌套你的let/before塊來實現你的不同的測試用例 – nicolas

+0

你正在談論哪個Devise/RSpec版本?因爲在Devise 4.20 Devise :: TestHelpers已被棄用,但包括Devise :: Test :: ControllerHelpers,它僅適用於ActionController :: TestCase,但不適用於RSpec? – Klaus