Home > OS >  Is there a way to maintain the login status in Capybara?
Is there a way to maintain the login status in Capybara?

Time:06-01

For example, open the browser in the following code and log in to Google in manual.

require "bundler/inline"

gemfile do
  source "https://rubygems.org"
  gem "webdrivers"
  gem "capybara", require: "capybara/dsl"
end

Capybara.current_driver = :selenium_chrome

Capybara.visit("https://www.google.co.jp/")
gets

However, if I execute it again, the login status will be canceled, and if it is 2FA, it is very troublesome.

Is there a good way?

CodePudding user response:

Capybara is designed as a testing framework, not a web-scraping framework (although some people use if for that). As such, tests are meant to be isolated from each other and Capybara does a bit of work to try and make sure that happens. This means that in each test you need to re-authenticate if necessary for that test, and that is best handled by using the testing mode of whatever authentication library the application under test is using.

If instead you're using Capybara for web-scraping you could look at configuring the selenium driver to use a specific user profile, so cookies get saved and reused. You may also need to override Capybaras session#reset method to prevent cookies from being cleared, but Capybara really isn't designed for that use case.

  • Related