Search code examples
scalafuturespecs2matcher

Re-use "await" parameters in Scala Specs2


Suppose I am testing results of Futures (see below) with specs2.

def f1():Future[String] = {...}
def f2():Future[String] = {...}

I have Matchers[String] to check the results

def m1():Matcher[String] = {...}
def m2():Matcher[String] = {...}

Now I can use implicits to create Matcher[Future[String]].

def fm1():Matcher[Future[String]] = m1.await(retries=2, timeout=2.seconds)
def fm2():Matcher[Future[String]] = m2.await(retries=2, timeout=2.seconds)   

So far so good, but I don't like that repeating retries = 2 and timeout = 2.seconds. How can I define them just once and reuse them across all await calls in the spec ?


Solution

  • case class Retry(value:Int) extends AnyVal
    case class Timeout(value:Duration) extends Anyval
    
    implicit class MatcherWithImplicitValues[A](m:Matcher[A]) {
      def awaitWithImplicitValues(implicit r:Retry, t:Timeout) = {
        m.await(retries = r.value, timeout = t.value)
      }
    }
    
    implicit val retries = Retry(2)
    implicit val timeout = Timeout(2 seconds)
    
    m1.awaitWithImplicitValues