Search code examples
unit-testingscalaspecs2

Execute specs2 examples wrapped in function


How can I execute all tests for a spec2 Specification in a wrapper function?

ex:

class HelloWorldSpec extends Specification {

    wrapAll(example) = {
        // wrap it in a session, for example.
        with(someSession){
            example()
        }
    }

    "The 'Hello world' string" should {
      "contain 11 characters" in {
        "Hello world" must have size(11)
      }
      "start with 'Hello'" in {
        "Hello world" must startWith("Hello")
      }
      "end with 'world'" in {
        "Hello world" must endWith("world")
      }
    }
  }

So, each of these 3 tests should be executed inside the

with(someSession){...

When using ScalaTest, I could do that overriding withFixture


Solution

  • You can use something like AroundExample:

    class HelloWorldSpec extends Specification with AroundExample {
      def around[T <% Result](t: =>T) = inWhateverSession(t)
      ...
    }
    

    Or an implicit context object:

    class HelloWorldSpec extends Specification {
      implicit object sessionContext = new Around {
        def around[T <% Result](t: =>T) = inWhateverSession(t)
      }
      ...
    }
    

    Depending on exactly what you need to do, some combination of the Before, BeforeAfter, or Outside contexts (and their Example counterparts) might fit more appropriately.