How to change the hostname in Cucumber features

Updated . Posted . Visible to the public.

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

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.

Arne Hartherz
Last edit
Dominik Schöler
Keywords
stub, request, response
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2012-11-27 10:41)