Capturing screenshots in Watir-Webdriver & Cucumber

Update: 29 August – Thanks to Rob Hunter for the screenshot embed trick

When you’re running a suite of automated tests and one fails, I find it handy to capture a screenshot of the browser so it’s easier to investigate. Fortunately this is easier than ever before with Watir-Webdriver and it’s inbuilt save_screenshot method.

If you’re using Cucumber, you’ll be looking for something like this:

After do |scenario|
  if scenario.failed?
    Dir::mkdir('screenshots') if not File.directory?('screenshots')
    screenshot = "./screenshots/FAILED_#{scenario.name.gsub(' ','_').gsub(/[^0-9A-Za-z_]/, '')}.png"
    Browser::BROWSER.driver.save_screenshot(screenshot)
    embed screenshot, 'image/png'
  end
end

The neatest thing about this method is that it captures the entire browser page, not just what is displayed without scrolling (see a screenshot of my blog below).

I hope you find this handy, I think it’s awesome.

9 thoughts on “Capturing screenshots in Watir-Webdriver & Cucumber

  1. I can not make this to work on watir-webdriver. When I call the @browser_instance.screenshot.save “filename.png”
    it complains about the screenshot method.
    I already required watir-webdriver/screenshot.rb, but still not working.
    Please help

  2. I am also new to ruby and watir. Can this solution be used with rspec and not just cucumber? How will my test detect the failure and know when to call this After method. Thanks for any help or direction.

    • Not sure about rspec, but regarding your second question: After method will be always called after scenario finished its work. If you have any failure in any watir-webdriver wrapper of cucumber scenario statements, so After method will know that scenario is failed and you definitely can do screenshot using simple ‘if’ clause and in-build method of watir-webdriver

  3. If you want to create a HTML report you can pass around solo, without having to bundle it up with the screenshot files etc, you may want to embed the screenshot into the report and not just a link to it.

    encoded_img = @browser.driver.screenshot_as(:base64)
    embed(“data:image/png;base64,#{encoded_img}”,’image/png’)

  4. can I use this with minitest? It did not work. Please let me know how to get screen shots in minitest.

Comments are closed.