Read more

Cucumber step to set cookies in your Capybara session

Arne Hartherz
March 20, 2013Software engineer at makandra GmbH

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
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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.

Posted by Arne Hartherz to makandra dev (2013-03-20 18:23)