Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a cookie from Capybara's default Rack::Test driver?

Tags:

capybara

In my non-JS Capybara tests, I want to assign a cookie. How can I do that?

Wrote my own answer below.

like image 448
Henrik N Avatar asked Mar 19 '23 14:03

Henrik N


1 Answers

Solved it.

headers = {}
Rack::Utils.set_cookie_header!(headers, name, value)
cookie_string = headers["Set-Cookie"]
Capybara.current_session.driver.browser.set_cookie cookie_string

Based on this.

If you need to support both Rack::Test and Poltergeist:

def set_cookie(name, value)
  if Capybara.current_session.driver.respond_to?(:set_cookie)
    # Poltergeist driver (JS)
    Capybara.current_session.driver.set_cookie(name, value)
  else
    # Rack::Test driver (non-JS)
    headers = {}
    Rack::Utils.set_cookie_header!(headers, name, value)
    cookie_string = headers["Set-Cookie"]
    Capybara.current_session.driver.browser.set_cookie cookie_string
  end
end

There may be escaping issues since it's just interpolated; worked fine for my needs though.

like image 114
Henrik N Avatar answered May 01 '23 15:05

Henrik N