In my non-JS Capybara tests, I want to assign a cookie. How can I do that?
Wrote my own answer below.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With