środa, 24 lutego 2016

Take screenshot in IntegrationTest with capybara when it fails

This is about saving screenshot on failing tests in capybara. There are bunch of advices how to do this in rspec but none for ActionDispatch::IntegrationTest. There is also a gem for this capybara-screenshot but I haven't got luck with this at all.

Here is how to do this with rails 4 integration test. Under the hood it uses minitest that have bunch of hooks we can use.

# test/test_helper.rb
class ActionDispatch::IntegrationTest
def after_teardown
if !passed?
timestamp = "#{Time.zone.now.strftime('%Y-%m-%d-%H:%M:%S')}"
screenshot_name = "screenshot-#{timestamp}.png"
# Handle CircleCi too
screenshot_path = "#{ENV.fetch('CIRCLE_ARTIFACTS', Rails.root.join('tmp/capybara'))}/#{screenshot_name}"
page.save_screenshot(screenshot_path)
end
super
end
end
view raw test_helper.rb hosted with ❤ by GitHub

Most of code stolen from http://vumanhcuongit.github.io/testing/2016/01/26/take-screenshot-when-cucumber-test-failed/ and https://github.com/mattheworiordan/capybara-screenshot