2013-05-18 22 views
1
斯波克測試動作

我有我想測試時,內容類型的動作是application/json在Grails的

我的行動看起來是這樣的:

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是從未到達控制器......?

+0

JS是Javascript,使用 'JSON' 內withFormat代碼來處理JSON。 – dmahapatro

+0

我已經改變了,但仍然是相同的錯誤。我認爲json沒有被傳遞給控制器​​。 – Anthony

+0

在測試中請求設置'content-type'之前,您正在調用該操作。 – dmahapatro

回答

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" 
    }