Read more

How to change the hostname in Cucumber features

Arne Hartherz
November 27, 2012Software engineer at makandra GmbH

Capybara uses www.example.com as the default hostname when making requests.
If your application does something specific on certain hostnames and you want to test this in a feature, you need to tell Capybara to assume a different host.

Given /^our host is "([^\"]+)"$/ do |host|
  page.config.stub app_host: "http://#{host}"
  
  # In older Capybaras (< 2.15) you needed to do this instead:
  Capybara.stub app_host: "http://#{host}"
end
Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

You can now say:

When I go to the start page
Then I should not see "Home of Foo"

When our host is "foo.example.com"
  And I go to the start page
Then I should see "Home of Foo"

The host will be stubbed for the remainder of one scenario and restored after each scenario (i.e. you do not need an After step to clean up).


Notes:

  • Selenium tests will actually visit the app_host, so you can't really use it for those. Here are some alternatives:
    • Resort to a hack, like a flag on a service model that makes your methods behave like you are on the correct host.
    • Stub app_host to something like foo.example.vcap.me:12345 (vcap.me and any of its subdomains will resolve to localhost). Remember to set the port.
  • Setting Capybara.app_host = ... would also work, but bleed into other scenarios!

If you want to stub the request IP address, there is also a card about that.

Posted by Arne Hartherz to makandra dev (2012-11-27 11:41)