0
votes

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(By.id("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 ScreenshotOnFailure.scala, 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?

1

1 Answers

1
votes

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: https://stackguides.com/questions/3422262/take-a-screenshot-with-selenium-webdriver
      }
      outcome
   }
}

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(By.id("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.