Created
September 2, 2024 07:56
-
-
Save N0xFF/00e7cdf26f0a08fb08f282f842d19bdf to your computer and use it in GitHub Desktop.
Save/show browser logs (Chome + Selenium + Capybara + Rails)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase | |
Capybara.register_driver :chrome_headless do |app| | |
client = Selenium::WebDriver::Remote::Http::Default.new | |
client.read_timeout = ENV.fetch("SELENIUM_READ_TIMEOUT", 120).to_i | |
options = Selenium::WebDriver::Chrome::Options.new | |
options.add_argument('--headless=new') if ENV["HEADLESS"] != "false" | |
options.add_argument('--disable-extensions') | |
options.add_argument('--disable-gpu') | |
options.add_option("goog:loggingPrefs", { browser: "ALL" }) | |
if ENV["CI"].present? || ENV["CODESPACES"].present? | |
options.add_argument('--no-sandbox') | |
options.add_argument('--disable-dev-shm-usage') | |
end | |
driver_arguments = { | |
http_client: client, | |
browser: :chrome, | |
# List https://chromedriver.chromium.org/capabilities | |
options: options, | |
clear_local_storage: true, | |
clear_session_storage: true | |
} | |
Capybara::Selenium::Driver.new(app, **driver_arguments) | |
end | |
def self.browser_logger | |
@browser_logger ||= Logger.new( | |
Rails.root.join("log", "browser.log"), | |
formatter: proc { |_, _, _, msg| msg } | |
) | |
end | |
def self.logger_formatter | |
@logger_formatter ||= Logger::Formatter.new | |
end | |
def browser_logger | |
self.class.browser_logger | |
end | |
def logger_formatter | |
self.class.logger_formatter | |
end | |
def before_teardown | |
# Get browser console logs. | |
# | |
# You can test it using: | |
# — `execute_script("console.error('This is error')")`. | |
# — `execute_script("console.info('This is info')")`. | |
# — `execute_script("console.log('This is log')")`. | |
browser_logs = page.driver.browser.logs.get(:browser) | |
browser_logs.each do |log| | |
browser_logger.unknown do | |
# Keep microseconds and local machine timezone | |
seconds, microseconds = log.timestamp.divmod(1000) | |
time = Time.at(seconds, microseconds * 1000) | |
# Write log message with test name | |
logger_formatter.call(log.level, time, name, log.message) | |
end | |
end | |
super | |
end | |
def browser_logs | |
page.driver.browser.manage.logs.get(:browser) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment