Tôi biết đây là một câu hỏi tương đối cũ, nhưng tôi đã phát hiện ra rằng điều này phụ thuộc vào loại bài kiểm tra bạn đang chạy. Tôi cũng đang chạy Rails 4 và RSpec 3.2, vì vậy tôi chắc chắn một số điều đã thay đổi kể từ khi câu hỏi này được hỏi.
Yêu cầu Specs
before { host! "#{mock_subdomain}.example.com" }
Specs Feature với Capybara
before { Capybara.default_host = "http://#{mock_subdomain}.example.com" }
after { Capybara.default_host = "http://www.example.com" }
Tôi thường tạo module trong spec/support
rằng giống như thế này:
# 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
Include in spec/rails_helper.rb
:
RSpec.configure do |config|
# ...
# Extensions
config.extend FeatureSubdomainHelpers, type: :feature
config.extend RequestSubdomainHelpers, type: :request
end
Sau đó, bạn có thể gọi trong spec của bạn như sau:
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
Nguồn
2015-05-23 13:55:59
một mẹo nhỏ - yêu cầu là availab le như một phương thức cũng như một biến mẫu. Nó có thể tốt hơn để truy cập nó thông qua phương pháp, để giữ một khoảng cách nhỏ giữa bạn và mã RSpec cơ bản. – pat
Tôi có thể hỏi làm thế nào nó được thực hiện theo cách phương pháp? – lulalala
@lulalala 'request.host =" # {mock_subdomain} .example.com "' – alf