我正在使用rSpec來測試我的應用程序。在我的應用程序控制器中,我有如下方法:Rails rspec設置子域
def set_current_account
@current_account ||= Account.find_by_subdomain(request.subdomains.first)
end
是否可以在我的規範中設置request.subdomain?也許在前面的塊?我是rSpec的新手,所以對此的任何建議都會非常感謝。
Eef
我正在使用rSpec來測試我的應用程序。在我的應用程序控制器中,我有如下方法:Rails rspec設置子域
def set_current_account
@current_account ||= Account.find_by_subdomain(request.subdomains.first)
end
是否可以在我的規範中設置request.subdomain?也許在前面的塊?我是rSpec的新手,所以對此的任何建議都會非常感謝。
Eef
我想出瞭如何分類這個問題。
在我面前擋在我的規格,我只是說:
before(:each) do
@request.host = "#{mock_subdomain}.example.com"
end
此設置了request.subdomains.first是mock_subdomain的價值。
希望有人認爲這很有用,因爲它在網上其他任何地方都沒有很好地解釋。
在rails 3中,我試圖手動設置主機沒有工作,但看着代碼,我注意到他們很好地解析了你傳遞給請求幫助者的路徑,如get
。 果然,如果你的控制器進入並獲取子域中並存儲中提到的用戶作爲@king_of_the_castle
it "fetches the user of the subomain" do
get "http://#{mock_subdomain}.example.com/rest_of_the_path"
assigns[:king_of_the_castle].should eql(User.find_by_name mock_subdomain)
end
我知道這是一個比較老的問題,但我發現,這要看什麼樣的測試你正在運行。我也運行Rails 4和RSpec 3.2,所以我肯定有些事情自從問了這個問題後就改變了。與水豚
before { Capybara.default_host = "http://#{mock_subdomain}.example.com" }
after { Capybara.default_host = "http://www.example.com" }
我通常在spec/support
創建模塊看起來像這樣
請求規格
before { host! "#{mock_subdomain}.example.com" }
功能規格:
# spec/support/feature_subdomain_helpers.rb
module FeatureSubdomainHelpers
# Sets Capybara to use a given subdomain.
def within_subdomain(subdomain)
before { Capybara.default_host = "http://#{subdomain}.example.com" }
after { Capybara.default_host = "http://www.example.com" }
yield
end
end
# spec/support/request_subdomain_helpers.rb
module RequestSubdomainHelpers
# Sets host to use a given subdomain.
def within_subdomain(subdomain)
before { host! "#{subdomain}.example.com" }
after { host! "www.example.com" }
yield
end
end
包括在spec/rails_helper.rb
:
RSpec.configure do |config|
# ...
# Extensions
config.extend FeatureSubdomainHelpers, type: :feature
config.extend RequestSubdomainHelpers, type: :request
end
那麼您可以在規範中調用,像這樣:
feature 'Admin signs in' do
given!(:admin) { FactoryGirl.create(:user, :admin) }
within_subdomain :admin do
scenario 'with valid credentials' do
# ...
end
scenario 'with invalid password' do
# ...
end
end
end
您好,先生,謝謝! – 2016-08-10 10:34:20
克里斯·彼得斯的回答爲我工作要求的規格,但是對於功能規格,我不得不作出以下修改:
rails_helper:
Capybara.app_host = 'http://lvh.me'
Capybara.always_include_port = true
feature_subdomain_helpers:
module FeatureSubdomainHelpers
def within_subdomain(subdomain)
before { Capybara.app_host = "http://#{subdomain}.lvh.me" }
after { Capybara.app_host = "http://lvh.me" }
yield
end
end
一個小提示 - 請求是可用的le作爲一種方法以及一個實例變量。通過該方法訪問它可能會更好,以保持與底層RSpec代碼之間的距離。 – pat 2010-08-03 05:04:45
請問這是怎麼做的方法嗎? – lulalala 2012-05-14 06:12:22
@lulalala'request.host =「#{mock_subdomain} .example.com」' – alf 2012-08-15 03:27:48