简体   繁体   中英

How to access cookies (Capybara/Selenium Chrome Webdriver)

I've been able to find loads and loads of examples that claim that page.driver.cookies should work but there is no such method on Selenium::WebDriver::Chrome::Driver (which is what page.driver is).

I've been trying to dig around with pry to find anything that responds to cookies , cookie_jar , set_cookie or clear_cookies but there seems to be nothing. Not on page , page.driver or page.driver.browser .

I also don't quite get the sentiment that reading cookies isn't a thing in testing (the RackTest driver exposes #cookie_jar but Rack::Test::Methods only forwards set_cookie and clear_cookies ). Why shouldn't I test a middleware that sets a cookie under certain conditions?

The reason you shouldn't be testing cookies directly, is because feature/system tests are the wrong place for that. Those types of tests are designed to test things from a users perspective, and users don't actually see cookies they just see the behaviors cookies enable. Therefore, in Capybara tests, you should just be testing the behaviors enabled by cookies not that the actual cookies are set. The setting/clearing of cookies is really something that should be tested for in controller or request tests.

If you still insist on accessing cookies directly then they are accessible using JS via evaluate_script or via selenium driver specific methods page.driver.browser.manage.all_cookies , etc. - although any time you're calling page.driver.xxx you're probably doing something you shouldn't be.

Just from reading this documentation , have you tried something like this:

require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome

begin
  driver.get 'https://www.example.com'

  # Adds the cookie into current browser context
  driver.manage.add_cookie(name: "key", value: "value")
ensure
  driver.quit
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM