Anthony
Anthony

Reputation: 36008

Testing action with spock in Grails

I have an action that I would like to test for when content-type is application/json

My action looks like this:

def save () {
  request.withFormat {
     json {
        def colorInstance = new Color(params.colors)
        render "${colorInstance.name}"
     }

     html {
       //do html stuff
     }
  }

I've got the following but it doesn't seem to work:

def "js test" () {
    when:
    controller.save()
    request.contentType = "application/json"
    request.content = '{"colors": {"name": "red"} }'

    then:
    response.contentAsString == "red"
}

I believe the problem is in the way I'm sending json to the controller in my test. Is this the correct way?

Error is:

response.contentAsString == "red"
|        |               |
|        null            false

If I slightly modify the controller to be:

     json {
        def colorInstance = new Color(params.colors)
        render "${params.colors}"
     }

then also the error is same:

response.contentAsString == "red"
|        |               |
|        null            false

So I suspect that params.colors is never reached to the controller...?

Upvotes: 1

Views: 1571

Answers (1)

dmahapatro
dmahapatro

Reputation: 50275

This works for me:

Note:- I used given to set parameters. Looks like setting as JSON to request also binds to params in controller.

def save() {
        request.withFormat {
            json {
                def colorInstance = new Color(params.colors)
                render "${colorInstance.colorName}"
            }

            html {
                //do html stuff
            }
        }
    }

//Domain Color

class Color {
    String colorName
    Boolean isPrimaryColor
}

//Spock Test

def "json test" () {
        given:
            request.contentType = "application/json"
            request.JSON = '{colors: {colorName: "red", isPrimaryColor: true} }'
        when:
            controller.save()
        then:
            assert response.status == 200
            assert response.contentAsString == "red"
    }

Upvotes: 3

Related Questions