Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

Output browser logs on failed feature test

Christophe Bliard22c271c4d96f
diff --git a/spec/support/capybara.rb b/spec/support/capybara.rb
index 4b98fe3b401..b81e4e1db34 100644
--- a/spec/support/capybara.rb
+++ b/spec/support/capybara.rb
@@ -52,3 +52,66 @@ end
Rails.application.config do
config.middleware.use RackSessionAccess::Middleware
end
+
+# Capture browser logs on failed examples and output them in Progress and
+# Documentation formatters.
+module Capybara::CaptureBrowserLogs
+ RSPEC_TEXT_FORMATTERS = [
+ "RSpec::Core::Formatters::ProgressFormatter",
+ "RSpec::Core::Formatters::DocumentationFormatter"
+ ].freeze
+
+ class << self
+ def after_failed_example(example)
+ return unless example.example_group.include?(Capybara::DSL)
+ return unless failed?(example)
+ return if Capybara.page.current_url.blank?
+
+ logs = Capybara.page.driver.browser.manage.instance_variable_get(:@bridge).log("browser")
+ example.metadata[:browser_logs] = logs
+ rescue StandardError => e
+ warn "Unable to get browser logs: #{e}"
+ end
+
+ def change_text_formatter_to_output_captured_browser_logs
+ RSpec.configuration.formatters.each do |formatter|
+ next unless RSPEC_TEXT_FORMATTERS.include?(formatter.class.to_s)
+ next if formatter.singleton_class.included_modules.include?(TextReporter)
+
+ formatter.singleton_class.prepend(TextReporter)
+ end
+ end
+
+ def failed?(example)
+ # reusing private method from capybara-screenshot gem
+ Capybara::Screenshot::RSpec.send(:failed?, example)
+ end
+ end
+
+ module TextReporter
+ def example_failed(notification)
+ super
+ output_browser_logs(notification.example)
+ end
+
+ private
+
+ def output_browser_logs(example)
+ return unless example.metadata[:browser_logs]
+
+ logs = example.metadata[:browser_logs]
+ output.puts(" Browser logs:\n #{logs.join("\n ")}")
+ end
+ end
+end
+
+# Output browser logs after failed feature test
+RSpec.configure do |config|
+ config.after(type: :feature) do |example|
+ Capybara::CaptureBrowserLogs.after_failed_example(example)
+ end
+
+ config.before(:suite) do
+ Capybara::CaptureBrowserLogs.change_text_formatter_to_output_captured_browser_logs
+ end
+end