A very quick note about testing using Cucumber and Webrat when using subdomains, in case it helps anyone (or perhaps my future self when I no longer remember this little detail in six months time).
Today I was working on a feature which had as one of its requirements that the user go to a special admin subdomain in order to log in to the admin system. This was blowing up all over the place, but we’ve now got it working alright. The first thing to realize is that Cucumber/Webrat need to be told about your subdomain. We first tried dumping the following into Cucumber’s env file:
def use_admin_subdomain
host! "#{::ADMIN_SUBDOMAIN}.test.host"
end
Our reasoning was that Rails normally runs its functional tests with a @request.host value of “test.host”, so if we wanted to shift things around, we figured we could just stick the admin subdomain on the front of that host and everything would be peachy. We put use_admin_subdomain at the top of our admin_steps, like so:
Given /^I am logged in as an admin user$/ do
use_admin_subdomain
Given %q{An admin user with username "admin@example.com" and password "password"}
And %q{I log in with username "admin@example.com" and password "password"}
end
The result:
Then I should see "Thing was successfully created." # features/step_definitions/webrat_steps.rb:118
expected the following element's content to include "Thing was successfully created.":
You are being redirected. (Spec::Expectations::ExpectationNotMetError)
features/admin_manage_thing.feature:16:in `Then I should see "Thing was successfully created."'
Failing Scenarios:
cucumber features/admin_manage_thing.feature:9 # Scenario: Create Thing
We scratched our heads and outputted the failing page into the browser. Weirdly, it just had a message in it saying “You are being redirected” with a link to the redirect. After doing a bit of research, we figured out that this happens because Cucumber/Webrat run tests in the www.example.com domain, so we were effectively trying to redirect in our tests from admin.test.host to www.example.com and Rails didn’t like doing that very much.
Changing our use_admin_subdomain method to do this instead worked great:
def use_admin_subdomain
host! "#{::ADMIN_SUBDOMAIN}.example.com"
end
This works because Rails is happy to do subdomain redirects and doesn’t display that weird “you are being redirected” page. And now, back to the code!
