Skip to content

Instantly share code, notes, and snippets.

@noniq
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noniq/9289157 to your computer and use it in GitHub Desktop.
Save noniq/9289157 to your computer and use it in GitHub Desktop.
RSpec + Capybara: Include link to saved HTML and screenshot for failed examples.
# Add this to your spec_helper.rb (needs Ruby 2 because of `Module#prepend`)
#
# It does two things:
#
# 1. For each failed feature spec, save the HTML page and (if possible) a screenshot
# to "#{Rails.root}/tmp/capybara/".
#
# 2. Extend RSpec’s HTML output to include links to the saved HTML page and screenshot
# for failed examples. Works with both the regular HTML formatter and the TextMate
# formatter.
module LinkToScreenshotsOnFailure
def extra_failure_content(exception)
example = @failed_examples.last
files = example.metadata[:saved_files]
content = super
if files.present?
link_to = ->(title, local_path){
return "" unless local_path
url = URI.escape("file://#{local_path}")
title = CGI.escape_html(title)
%{<a onclick='if (TextMate) { TextMate.system("open #{Shellwords.escape(url)}"); return false; }' href='#{url}' style='margin-right: 10px'><b>#{title}</b></a>}
}
content << "<p>Saved files: "
content << link_to["HTML page", files[:page]]
content << link_to["Screenshot", files[:screenshot]]
content << "</p>"
end
content
end
end
RSpec.configure.do |config|
config.before(:suite) do
RSpec.configuration.formatters.each do |formatter|
formatter.class.send(:prepend, LinkToScreenshotsOnFailure) if formatter.is_a?(RSpec::Core::Formatters::HtmlFormatter)
end
end
config.after(:each) do |example|
if example.metadata[:type] == :feature and example.exception.present?
example.metadata[:saved_files] = {}
name = "#{Rails.root}/tmp/capybara/error-#{Time.new.strftime("%Y%m%d%H%M%S")}#{rand(10**10)}"
save_page("#{name}.html")
example.metadata[:saved_files][:page] = "#{name}.html"
begin
save_screenshot("#{name}.png")
example.metadata[:saved_files][:screenshot] = "#{name}.png"
rescue Capybara::NotSupportedByDriverError
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment