Is there a way to print javascript console.errors to the terminal with Rspec/Capybara/Selenium?
There's a code sample at the end of this gist https://gist.github.com/gkop/1371962 (the one from alexspeller) which worked very nicely for me.
I ended up doing this in the context of the JS tests I was trying to debug
after(:each) do errors = page.driver.browser.manage.logs.get(:browser) if errors.present? message = errors.map(&:message).join("\n") puts message endend
Here is another way, currently working with Selenium and headless Chrome (should also work with Firefox).
Add the following to spec/rails_helper.rb
, within the RSpec.configure do |config|
block and all feature specs with js: true
metadata will display JS errors.
class JavaScriptError< StandardError; endRSpec.configure do |config| config.after(:each, type: :feature, js: true) do |spec| errors = page.driver.browser.manage.logs.get(:browser) .select {|e| e.level == "SEVERE" && e.message.present? } .map(&:message) .to_a if errors.present? raise JavaScriptError, errors.join("\n\n") end endend
The code is an adaptation of this.
This isn't pretty, but you could inject a script to direct errors into the DOM and watch for those changes via Selenium.
More specifically, inject a script into each page which overrides window.onerror
or console
such that errors append the information to some hidden node you've injected into the DOM. Then, via Selenium, periodically check for and empty the contents of that element, printing the emptied data to the Java console.