Search code examples
groovyspockratpack

How do I set POST Parameters in a TestHttpClient


I'm using Ratpack's TestHttpClient to send a POST request in a Spock test for a REST API. The API's endpoint accepts the parameter myPostParam as part of the request body / POST parameter.

I see that there is a post method, that performs the POST request, but I don't know how I can send the parameter myPostParam=123456

import ratpack.groovy.test.GroovyRatpackMainApplicationUnderTest
import ratpack.test.http.TestHttpClient
import ratpack.test.ServerBackedApplicationUnderTest
import spock.lang.Specification

class MyApiSpecification extends Specification {

  ServerBackedApplicationUnderTest aut = new GroovyRatpackMainApplicationUnderTest()
  @Delegate
  TestHttpClient client = testHttpClient(aut)

  def "Doing a API call for Stackoverflow"() {
    given:
    int myPostParam = 123456

    when:
    post("/api/v1.0/someMethod/")
    // TODO: How do I add "myPostParam=$myPostParam" to the request body?

    then:
    response.statusCode == 201
    response.body.text.empty
  }
}

Solution

  • You can use TestHttpClient.params(action) to set request parameters. Something like this should do the trick:

    import ratpack.groovy.test.GroovyRatpackMainApplicationUnderTest
    import ratpack.test.http.TestHttpClient
    import ratpack.test.ServerBackedApplicationUnderTest
    import spock.lang.Specification
    
    class MyApiSpecification extends Specification {
    
      ServerBackedApplicationUnderTest aut = new GroovyRatpackMainApplicationUnderTest()
      @Delegate
      TestHttpClient client = testHttpClient(aut)
    
      def "Doing a API call for Stackoverflow"() {
        given:
        int myPostParam = 123456
    
        when:
        params({ params ->
          params.put("myPostParam", myPostParam)
        }).post("/api/v1.0/someMethod/")
    
        then:
        response.statusCode == 201
        response.body.text.empty
      }
    }