Taking a Screenshot On Failure

The Problem

With browser tests it can often be challenging to track down the issue that triggered a failure.

A Solution

A quick and easy way to gain some insight into your test failures is by capturing screenshots on test failures. Let's dig in with an example.

An Example

We start things off by including our libraries for driving the browser and performing assertions and then wire up setup and teardown actions.

require 'selenium-webdriver'
require 'rspec-expectations'

def setup
  @driver = Selenium::WebDriver.for :firefox

def teardown

Next we wire up our run action. In it we call setup and teardown, sandwiching between them a yield with exception handling.

def run
  rescue StandardError => error
    puts error.message
    @driver.save_screenshot "./#{Time.now.strftime("failshot__%d_%m_%Y__%H_%M_%S")}.png"

This is what is responsible for taking screenshots on failure. When we call the run block and pass it commands, it will evaluate them within the begin/rescue exception handling. If there is a failure, it will rescue, output the failure message to the terminal, and take a screenshot (placing it in the current working directory).

A couple of things to note:

  • We rescue StandardError rather than Exceptions since that would cover everything instead of just test failures
  • We are using a timestamped filename (down to the second). So each screenshot should be unique and in the order taken. For more information on how we are manipulating the Time object, check out the documentation for strftime -- a.k.a. String Formatted Time.
run do
  @driver.get 'http://www.google.com'
  @driver.title.should_not == 'Google'

And lastly, we wire up our test actions in the run block. It goes to Google and checks the title. We want to trigger a failure, so we assert that the page title does not include the text 'Google'.

Expected Behavior

  • Load Google
  • Check that the page title does not contain 'Google'
  • Output a failure message in the terminal
  • Capture a timestamped screenshot in the current working directory


Hopefully this tip will help save you some time and make it easier to track down your test failures.

Happy Testing!

Found this helpful?

Submit your e-mail in the form below to recieve tips like this!

One email every Tuesday. No Spam. Ever. Unsubscribe anytime.

Back to the archives