Search code examples
scalaunit-testingmockitospecs2

specs2 - how to use the same variable inside around and inside the test itself?


I am using specs2 as my test framework. I want to generate a uniq key that will be available in the test itself.

def around[R: AsResult](r: => R): Result = {
   val uniqueToken = before()
   try AsResult(r)(uniqueToken)
   finally after(uniqueToken)
}

"foo" should {
   "bar" in {
     do something with uniqueToken
   }
}

Couldn't find any good way to do it.. Any idea?


Solution

  • You can write this

    class MySpec extends Specification with ForEach[Token] {
      "foo" should {
         "do something" in { token: Token =>
            ok
         }
      }
    
      def foreach[R : AsResult](f: Token => R): Result = {
        val token = createToken
    
        try AsResult(f(token))
        finally cleanup(token)
      }
    }
    

    This is documented here.