It works if I run cucumber features/subdomain.feature but it fails if I run cucumber features! It's unbelievable, but it's true. I logged current urls and it is subdomain.example.com for cucumber features/subdomain.feature and www.example.com for cucumber features for one scenario with

3 Answers
3

Okay, here is what should be a fairly straightforward and easy to understand hack of Capybara that yields the desired behavior, namely to be able to create a new session each time you switch subdomains. This is useful for sites where a user registers on one domain (which results in a subdomain being created for his account) and then ends up needing to navigate over to that subdomain.

First of all (and this part is fairly common to the other solutions out there) go ahead and give yourself a way to change Capybara.default_host in a Cucumber step. I did it like this:

Then /^I switch the subdomain to (\w+)$/ do |s|
Capybara.default_host = "#{s}.smackaho.st"
end

Stick this step into your Cucumber feature at the point where you want the new subdomain to be used. For example:

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

Now for the magical monkeypatching that makes this work. Basically, you want Capybara to be smart enough to detect when the subdomain has changed and reset its RackTest session object.

Yeah! Interesting solution. But it has one issue. If I use "show me the page", I got: expected: "/admin/companies", got: "/home/user/webdev/project/public/admin/companies" (using ==) (RSpec::Expectations::ExpectationNotMetError)
–
petRUShkaFeb 23 '11 at 20:17

And what the desctiption of step "Then I should be on the user confirmation page for acme"?
–
petRUShkaFeb 23 '11 at 20:23

Had the same problem for a bit with and my test had to sometimes switch or redirect back and forth between subdomains.

given this step:

When /^(?:|I )go to "(.+)"$/ do |url|
visit url
end

When I go to "http://mysubdomain.example.org" works in rack test, but if you are redirected by the app or follow a link to some other path the host reverts to the default_host.

There's a fork of rack-test by hassox that ensures that rack-test keeps track of the host used in the previous request.

So, in my Gemfile, before requiring capybara:

gem 'rack-test', :git => "https://github.com/hassox/rack-test.git"

Now if I need to hit a particular subdomain (or the app redirects me to one, like secure.myapp.com/sign_in) I'm sure that the feature can read more like a browser would behave: it will allow me to stay on the current subdomain until I go–using capybara's visit("somesubdomain.example.org")–or am redirected by the app to a different host.