2012-07-07 65 views
3

我正在嘗試使用OmniAuth和Devise編寫一個使用twitter進行登錄的集成測試。我無法獲取要設置的請求變量。它在控制器測試中工作,但不是集成測試,這導致我認爲我沒有正確配置規範助手。我環顧四周,但我似乎無法找到一個可行的解決方案。以下是我迄今爲止:Devise和OmniAuth twitter集成測試rspec

# spec/integrations/session_spec.rb 
require 'spec_helper' 
describe "signing in" do 
    before do 
    request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:twitter] 
    visit new_user_session_path 
    click_link "Sign in with twitter" 
    end 

    it "should sign in the user with the authentication" do 
    (1+1).should == 3 
    end 
end 

該規範raies一個錯誤,纔可以得到測試,我不太肯定要初始化的變量request需求。錯誤是:

Failure/Error: request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:twitter] 
    NoMethodError: 
    undefined method `env' for nil:NilClass 

現在我用的是request變量在我的控制器規範和測試通過,但它沒有被用於集成測試初始化​​。

# spec/spec_helper.rb 
Dir[Rails.root.join("spec/support/*.rb")].each {|f| require f} 
... 

# spec/support/devise.rb 
RSpec.configure do |config| 
    config.include Devise::TestHelpers, :type => :controller 
end 

感謝您的幫助!

回答

2

Devise測試助手僅用於控制器規格而不是集成規格。在水豚沒有請求對象,所以設置它不會工作。

你應該做的,而不是爲設計測試助手的範圍加載到控制器的規格,這樣的事情:https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara

class ActionController::TestCase 
    include Devise::TestHelpers 
end 

和使用水豚規格監獄長助手作爲本指南中的建議

有關更詳細的討論看看這個Github的問題頁面:https://github.com/nbudin/devise_cas_authenticatable/issues/36

2

Capybara README說:「訪問會話和請求是不可能從測試」,所以我放棄了在測試中進行配置並決定在application_controller.rb中編寫一個輔助方法。

before_filter :set_request_env 
def set_request_env 
    if ENV["RAILS_ENV"] == 'test' 
    request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:twitter] 
    end 
end 
1

在使用rspec + devise + omniauth + omniauth-google-apps進行測試期間,這一個適用於我。毫無疑問,Twitter的解決方案將是非常相似:

# use this method in request specs to sign in as the given user. 
def login(user) 
    OmniAuth.config.test_mode = true 
    hash = OmniAuth::AuthHash.new 
    hash[:info] = {email: user.email, name: user.name} 
    OmniAuth.config.mock_auth[:google_apps] = hash 

    visit new_user_session_path 
    click_link "Sign in with Google Apps" 
end 
0

當使用要求規範使用RSpec的新版本,它不允許訪問請求對象:

before do 
    Rails.application.env_config["devise.mapping"] = Devise.mappings[:user] # If using Devise 
    Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:twitter] 
end