Search code examples
scalaplayframeworkspecs2

Do a POST with Specs2 Fake Request


I want to perform a POST operation using FakeRequest + Specs2.

So far I have been able to write code for making a get request

class ItemsSpec extends PlaySpecification {
  "Items controller" should {
    "list items" in new WithApplication {
      route(FakeRequest(controllers.routes.Items.list())) match {
        case Some(response) => status(response) must equalTo (OK) contentAsJson(response) must equalTo (Json.arr())
        case None => failure
      }
    }
  }
}

Some of the difficulties which I am facing are

  1. use the reverse looking when doing post on the controller rather than hardcode the operation and path.

  2. Send json body as part of request

  3. parse the results and check if certain properties of the returned object match.

I did some googling and found this

https://www.playframework.com/documentation/2.4.x/ScalaTestingWithSpecs2

in the last example, it seems to be doing a POST. but the path is hardcoded and I don't understand what is essential action.

is there a simple way in which I can write a test case for my Web Service which requires a POST?


Solution

  • Something like this should work

    val Some(result) = route(FakeRequest(POST, controllers.routes.MyClassName.myMethod().url)
      .withJsonBody(Json.obj("key" -> 1234567)
    )
    

    Then check the results as normal. eg.

    status(result) must equalTo(OK)
    

    Edit - To read the body, assuming its Json, use this

    val js = contentAsJson(result)
    val fieldXyz = (js \ "fieldXyz").as[String]
    

    If you're just reading the body as a string, use this

    val resultString = contentAsString(result)