Capture browser console logs with capybara

Vivek Khurana picture Vivek Khurana · Sep 18, 2017 · Viewed 8.1k times · Source

I need to capture the console logs (category: info) of a browser using Ruby & Capybara. Until now I have tried using driver.manage.logs.get(:browser) or (:client) but, using this, the result is not what I want. It gives out the interaction results between selenium and browser where I can see my javascript statements sent for execution, but the resulting output fails to get captured.

Answer

Thomas Walpole picture Thomas Walpole · Sep 19, 2017

Whether or not logs are available when using selenium depends on what browser you are using with Selenium. If you were using Firefox you'd be out of luck since it doesn't support the log retrieval API, however since you're using Chrome they are accessible. The issue you're having is that, by default, only WARN or ERROR level logs are captured. You can change this in the driver registration through the loggingPrefs capability

Capybara.register_driver :logging_selenium_chrome do |app|
  caps = Selenium::WebDriver::Remote::Capabilities.chrome(loggingPrefs:{browser: 'ALL'})
  browser_options = ::Selenium::WebDriver::Chrome::Options.new()
  # browser_options.args << '--some_option' # add whatever browser args and other options you need (--headless, etc)
  Capybara::Selenium::Driver.new(app, browser: :chrome, options: browser_options, desired_capabilities: caps)
end

and then specify to use :logging_selenium_chrome as your driver

 Capybara.javascript_driver = :logging_selenium_chrome # or however else you're specifying which driver to use

which should then allow you to get the logs in your tests with

page.driver.browser.manage.logs.get(:browser)