Azher
Azher

Reputation: 493

Watir-webdriver: get same screenshot images for all failed scenarios

I've set screenshots to be taken when a scenario fails, but my html report shows the same screenshot on all failed scenarios. Can anyone help and let me know how I can get unique screenshots taken for each failed scenario.

Here is my code in my env.rb:

After do |scenario|
  if scenario.failed?
     @browser.driver.save_screenshot("screenshot.png")
     embed("screenshot.png", "image/png")
  end   

Upvotes: 3

Views: 1840

Answers (3)

jobwat
jobwat

Reputation: 9223

for the ones using RSpec, there is a really nice implementation of HtmlFormatter in the watir-rspec project

Upvotes: 0

Chuck van der Linden
Chuck van der Linden

Reputation: 6660

Justin has the answer, But while timestamps are fine, they make it harder when looking at the files to know which one was for what scenario. When I run tests while creating and debugging, I often don't even look at the html report, I just look at the generated screenshot, so in that case it is doubly useful to have more logical names.

So the code I use looks like this, and embeds using the scenario name

After do |scenario|
  if scenario.failed?
    screenshot = "./FAILED_#{scenario.name.gsub(' ','_').gsub(/[^0-9A-Za-z_]/, '')}.png"
    @browser.driver.save_screenshot(screenshot)
    encoded_img = @browser.driver.screenshot_as(:base64)
    embed("data:image/png;base64,#{encoded_img}",'image/png')
  end
end

An even more robust approach, dealing with scenario outlines and appending timestamp is described in this 'Two Four One' blog posting so far I've not needed to go that far, but I may pull in stuff from it to deal with scenario outlines.

Upvotes: 1

Justin Ko
Justin Ko

Reputation: 46836

You are saving the screenshot to the same file each time (ie overwriting the previous screenshot each time). The report has also linked all the images to the same place. This is why you get the same image everywhere.

You need to provide a unique name for the screenshot.

For example, you could timestamp (with date and time) the images:

After do |scenario|
  if scenario.failed?
     screenshot_file = "screenshot-#{Time.now.strftime('%Y%m%d-%H%M%S')}.png"
     @browser.driver.save_screenshot(screenshot_file)
     embed(screenshot_file, "image/png")
  end   
end

Upvotes: 4

Related Questions