Cucumber step to set cookies in your Capybara session

To set a cookie in your test browser for cucumber tests, you can use this step:

Given /^I have a "([^\"]+)" cookie set to "([^\"]+)"$/ do |key, value|
  headers = {}
  Rack::Utils.set_cookie_header!(headers, key, value)
  cookie_string = headers['Set-Cookie']

  Capybara.current_session.driver.browser.set_cookie(cookie_string)
end

Note that Rack::Utils is only used to find out the correct cookie header string (you don't want to generate it yourself) -- it is then passed to Capybara's browser. The browser will send the cookies when making the next request.

Use it like this in your features:

Given I have a "page_views" cookie set to "42"
When I visit the start page
Then something should happen

I only tried this on the Rack::Test browser. I do not know if it works for Selenium -- let me know if it does.


A word of advice

You should rarely care about doing the above. Usually, your integration tests should not be concerned with browser internals like cookies. However, if you want to test something like visitors with old cookies (which your application can't set any more) on the whole application stack, this is for you.

Arne Hartherz About 11 years ago