Search code examples
scalaplayframework-2.0specs2

Using pattern matching with Specs2 and Play in Scala


I have a simple problem with Scala/Play 2.0 and Specs.

This is my test

"Server" should {
"return a valid item with appropriate content type or a 404" in {
        val Some(result) = routeAndCall(FakeRequest(GET, "/item/1"))
        status(result) match {
            case 200 => contentType(result) must beSome("application/json")
            case 404 => true
            case _ => throw new Exception("The Item server did not return either a 200 application/json or a 404")
        }
        //false   --> It only compiles if I add this line!
 }
}
}

This doesnt compile because of the following:

 No implicit view available from Any => org.specs2.execute.Result.
[error]     "return a valid item with appropriate content type or a 404" in {
[error]                                                                  ^
[error] one error found

So Im thinking status(result) match is evaluating to Any hence the error. How should I specify that its result type is Result given that I am having a default case with a false return value?


Solution

  • I want to add one precision to Andrea's answer.

    Each branch indeed needs to give rise to a common type that can be converted to Result. The first branch type is MatchResult[Option[String]] and the second and third types are of type Result.

    There is a way to avoid the type annotation by using a MatchResult instead of a Result. ok and ko are 2 MatchResults, equivalent to success and failure, and can be used here:

    "return a valid item with appropriate content type or a 404" in {
      val Some(result) = routeAndCall(FakeRequest(GET, "/item/1"))
      status(result) match {
        case 200 => contentType(result) must beSome("application/json")
        case 404 => ok
        case _   => ko("The Item server did not return ... or a 404")
      }
    }