さて、これは、サブドメインを切り替えるたびに新しいセッションを作成できるという、望ましい動作を実現する、非常に単純で理解しやすい Capybara のハックです。これは、ユーザーが 1 つのドメインに登録し (その結果、アカウント用にサブドメインが作成される)、そのサブドメインに移動する必要があるサイトで役立ちます。
まず第一に (そして、この部分は他のソリューションにかなり共通しています)、先に進み、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
次に、これを機能させる魔法のモンキーパッチについて説明します。基本的に、サブドメインがいつ変更されたかを検出し、RackTest セッション オブジェクトをリセットできるように、Capybara を賢くする必要があります。
# 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 で動作しますが、修正しない限り別のバージョンでは動作しない可能性があります。幸運を。