Introducing the given keyword for specs2

Allow me to introduce the given keyword / function, written for use with specs2. It allows you to turn code like this:

val response = postRequest(url).response
response.status must_== OK
response.contentType must_== "application/json"
response.body must_== "{...}"

Into this:

given(postRequest(url).response) (
  _.status must_== OK,
  _.contentType must_== "application/json",
  _.body must_== "{...}"
)

Much better right? I find that the version that uses given is more readable, as it is better at communicating its intent. The intent is effectively always to put the spotlight on a value in order to inspect various aspects of it. In our example above, for instance, the spotlight was on the response.

It is also possible to nest the givens:

given(postRequest(url).response) (
  _.status must_== OK,
  _.contentType must_== "application/json",
  given(_.body.as[CreatedPost]) (
    _.subject must_== "The given keyword",
    _.author.name must_== "Pouria"
  )
)

The implementation of given it-self is quite simple:

import org.specs2.matcher.MatchResult

trait TestHelpers {
  def given[A, B](subject: A)(assertions: (A => MatchResult[B])*): MatchResult[Seq[B]] = {
    MatchResult sequence assertions.map(_(subject))
  }
}

Enjoy testing with given! Before you know it you’ll be addicted!