Tom Tom - 1 year ago 68
Scala Question

Screenshot on every failure using Scalatest

I would like to take a screenshot on every fail test in a Spec or Suite using ScalaTest.
The Scala Test website shows how to take screenshots surrounding every code that might fail with this:

withScreenshot {
drive.findElement("login")).getAttribute("value") should be ("Login")

There is this post that tries to explain, but I could not understand what exactly should be done.
I also found the class
, but could not use it, once it's private and has a package restriction.

Can anyone tell me if there's a way to intercept any failure and then take a screenshot?

Tom Tom
Answer Source

Just to have a final answer I'm writing the way I could solve the problem based on the approach from this post mentioned in the question.

In short, the solution ended up like this (pseudo-code).

trait Screenshots extends FunSpec {

   override def withFixture(test: NoArgTest): Outcome = {
      val outcome = test()

      // If the test fails, it will hold an exception.
      // You can get the message with outcome.asInstanceOf[Failure].exception
      if (outcome.isExceptional) {
         // Implement Selenium code to save the image using a random name
         // Check:

class MySpec extends Screenshots {

   describe("Scenario A") {
      describe("when this") {
         it("the field must have value 'A'") {
            // It will save a screenshot either if the selector is wrong or the assertion fails
            driver.findElement("elementA")).getAttribute("value") should be ("A")

From this point on, all Specs that extend the Screenshot trait will intercept errors and save a screenshot.

Just to complement, surrounding areas with withScreenshot(), as mentioned in the question, saves only failure on assertions, but it does not save a screenshot when the test fails due an element not found (e.g. wrong selector).

With the code above, all failures will save a screenshot.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download