使用JSON的Rack :: Test PUT方法无法将JSON转换为params

时间:2012-01-25 19:58:36

标签: ruby-on-rails-3 testing rest cucumber rspec-rails

我目前正在使用rails 3.1.3,cucumber-rails 1.2.1,rspec-rails 2.8.1和json_spec 0.8.0。我正在构建一个将由Android应用程序使用的restful Web服务API。我正在使用TDD / BDD实践,并且能够使用我的Cucumber步骤定义中的get()和post()成功测试Web服务操作。但是,当使用put()时,我遇到了一个问题。

这是我的device_update.feature:

Feature: Updating a Device
  The web service should accept a PUT request to update device settings.

  Scenario: The device information is updated when valid data is posted to the web service.
    Given a device exists
    When I put "/services/devices/4A3CABD4C4DE6E9F.json" with:
      """
      {
        "device": {
          "carrier": "SPRINT"
        }
      }
      """    
    Then the JSON should be:
      """
      {
        "message": "Device updated.",
        "response_code": 1
      }
      """

我的步骤定义是:

When /^I get "([^"]*)"$/ do |path|
  get(path)
end

When /^I post to "([^"]*)" with:$/ do |path, json_string|
  post(path, json_string, {"CONTENT_TYPE" => "application/json"})
end

When /^I put "([^"]*)" with:$/ do |path, json_string|
  put(path, json_string, {"CONTENT_TYPE" => "application/json"})
end

当测试运行时,我得到以下内容:

When I put "/services/devices/4A3CABD4C4DE6E9F.json" with:
  """
  {
    "device": {
      "carrier": "SPRINT"
    }
  }
  """
  You have a nil object when you didn't expect it!
  You might have expected an instance of Array.
  The error occurred while evaluating nil.[] (NoMethodError)
  ./app/controllers/services/devices_controller.rb:75:in `update'
  ./features/step_definitions/request_steps.rb:10:in `/^I put "([^"]*)" with:$/'
  features/services/devices/device_update.feature:7:in `When I put "/services/devices/4A3CABD4C4DE6E9F.json" with:'
Then the JSON should be:
  """
  {
    "message": "Device updated.",
    "response_code": 1
  }
  """

当我查看日志时,我看到以下内容:

Started PUT "/services/devices/4A3CABD4C4DE6E98.json" for 127.0.0.1 at 2012-01-25 11:36:16 -0800
Processing by Services::DevicesController#update as JSON
Parameters: {"{\n  \"device\": {\n    \"carrier\": "SPRINT"\n  }\n}"=>nil, "id"=>"4A3CABD4C4DE6E98"}

我截断了活动记录调用,因为它们不相关。很明显,JSON没有被转换成适当的参数,这就是为什么我得到一个意想不到的零。

有关如何使这项工作的任何想法?

1 个答案:

答案 0 :(得分:1)

您不应该将字符串传递给put。它负责转换为JSON字符串,这通常是一件好事。这里发生的事情是put再次将您的JSON字符串 JSONified

您应首先解析JSON字符串并将结果对象传递给put

When /^I put "([^"]*)" with:$/ do |path, json_string|
  payload = JSON.parse(json_string)
  put(path, payload, {"CONTENT_TYPE" => "application/json"})
end

此外,内容类型可能是不必要的。