Search code examples
scalaspecs2

Use specs2 matchers in an Around block


How does one run matchers from a separate class's function in an Around block in specs2?

Example (using Play framework):

class Spec extends Specification {
  "the application" should {
    "do something" in new WithBrowser { // <-- 1. because of this around block
      val runner = new Runner
      runner.check(browser)
    }
  }
}

class Runner extends MustMatchers {
  def check(browser: TestBrowser) = {
    browser.pageSource must contain("some text that isn't there") // <-- 2. this won't fail
  }
}

I read in the Around scaladoc that it doesn't work with matchers that don't throw FailureExceptions. Does this mean I have to check all the matchers myself? How else can I have my matchers fail?


Solution

  • By extending MustMatchers you unfortunately managed to avoid bringing in the all-important MustThrownExpectations trait, which has the following documentation:

    /**
    * This trait provides implicit definitions to transform any value into a 
    * MustExpectable, throwing exceptions when a match fails
    */
    

    If you follow all of the Specs2 traits all the way down from mutable.Specification, there's a trait MustThrownMatchers which will fail "the right way" for your use case; i.e.:

    class ThrowingRunner extends MustThrownMatchers {
      def check(browser: TestBrowser) = {
        browser.pageSource must contain("some text that isn't there")
      }
    }