好的,这应该是一个相当简单易懂的 Capybara hack,它产生了所需的行为,即每次切换子域时都能够创建一个新会话。这对于用户在一个域上注册(这会导致为其帐户创建一个子域)然后最终需要导航到该子域的站点很有用。
首先(这部分对于其他解决方案来说是相当常见的)继续并给自己一个在 Cucumber 步骤中更改 Capybara.default_host 的方法。我是这样做的:
Then /^I switch the subdomain to (\w+)$/ do |s|
Capybara.default_host = "#{s}.smackaho.st"
end
将此步骤粘贴到您希望使用新子域的 Cucumber 功能中。例如:
When I open the email
Then I should see "http://acme.rightbonus.com/users/confirmation" in the email body
Given I switch the subdomain to acme
When I follow "Click here to finish setting up your account" in the email
Then I should be on the user confirmation page for acme
现在是让这项工作发挥作用的神奇猴子补丁。基本上,您希望 Capybara 足够聪明,以检测子域何时发生更改并重置其 RackTest 会话对象。
# features/support/capybara.rb
class Capybara::Driver::RackTest
# keep track of the default host you started with
def initialize(app)
raise ArgumentError,
"rack-test requires a rack application, but none was given" unless app
@app = app
@default_host = Capybara.default_host
end
def process(method, path, attributes = {})
reset_if_host_has_changed
path = ["http://", @default_host, path].join
return if path.gsub(/^#{request_path}/, '') =~ /^#/
path = request_path + path if path =~ /^\?/
send(method, to_binary(path), to_binary( attributes ), env)
follow_redirects!
end
private
def build_rack_mock_session # :nodoc:
puts "building a new Rack::MockSession for " + Capybara.default_host
Rack::MockSession.new(app, Capybara.default_host || "www.example.com")
end
def reset_if_host_has_changed
if @default_host != Capybara.default_host
reset! # clears the existing MockSession
@default_host = Capybara.default_host
end
end
end
此补丁适用于 Capybara 0.4.1.1,除非经过修改,否则可能不适用于不同的版本。祝你好运。