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
我已經在微指令之前(每個)指定了。這不是訣竅嗎? –
應該像你一樣炒作,更新我的答案也許試試我提供的alt語法。如果你想要我的看法,但是你的ControllerMacro方法做了太多的事情,你可以設想讓用戶在不同的「上下文」塊中嵌套你的let/before塊來實現你的不同的測試用例 – nicolas
你正在談論哪個Devise/RSpec版本?因爲在Devise 4.20 Devise :: TestHelpers已被棄用,但包括Devise :: Test :: ControllerHelpers,它僅適用於ActionController :: TestCase,但不適用於RSpec? – Klaus