简体   繁体   English

如何访问 cookies(Capybara/Selenium Chrome Webdriver)

[英]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).我已经能够找到大量声称page.driver.cookies应该可以工作的示例,但是Selenium::WebDriver::Chrome::Driver上没有这种方法(这就是page.driver )。

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.我一直在尝试用 pry 挖掘任何响应cookiescookie_jarset_cookieclear_cookies的东西,但似乎什么都没有。 Not on page , page.driver or page.driver.browser .不在pagepage.driverpage.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 ).我也不太明白阅读 cookies 不是测试中的事情(RackTest 驱动程序公开#cookie_jarRack::Test::Methods仅转发set_cookieclear_cookies )。 Why shouldn't I test a middleware that sets a cookie under certain conditions?为什么我不应该测试在某些条件下设置 cookie 的中间件?

The reason you shouldn't be testing cookies directly, is because feature/system tests are the wrong place for that.您不应该直接测试 cookies 的原因是因为功能/系统测试是错误的地方。 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.这些类型的测试旨在从用户的角度进行测试,用户实际上并没有看到 cookies,他们只是看到了 cookies 启用的行为。 Therefore, in Capybara tests, you should just be testing the behaviors enabled by cookies not that the actual cookies are set.因此,在 Capybara 测试中,您应该只测试 cookies 启用的行为,而不是设置实际的 cookies。 The setting/clearing of cookies is really something that should be tested for in controller or request tests. cookies 的设置/清除确实应该在 controller 中进行测试或请求测试。

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.如果您仍然坚持直接访问 cookies 则可以使用 JS 通过evaluate_script或通过 selenium 驱动程序特定方法page.driver.browser.manage.all_cookies等访问它们 - 尽管任何时候您调用page.driver.xxx您都是可能做一些你不应该做的事情。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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