1

content-type が次の場合にテストしたいアクションがあります。application/json

私のアクションは次のようになります。

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

     html {
       //do html stuff
     }
  }

私は次のものを持っていますが、うまくいかないようです:

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

    then:
    response.contentAsString == "red"
}

問題は、テストでjsonをコントローラーに送信する方法にあると思います。これは正しい方法ですか?

エラーは次のとおりです。

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

コントローラーを次のように少し変更すると:

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

次に、エラーも同じです:

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

だから私はそれがコントローラーに到達していないと思うparams.colors...?

4

1 に答える 1

3

これは私のために働く:

注:- 以前givenはパラメータを設定していました。リクエストに対する設定もコントローラーJSONにバインドされているようです。params

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

            html {
                //do html stuff
            }
        }
    }

//ドメインの色

class Color {
    String colorName
    Boolean isPrimaryColor
}

//スポックテスト

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"
    }
于 2013-05-18T14:20:28.353 に答える