gpt4 book ai didi

ruby-on-rails-3 - Rack::Test 使用 JSON 的 PUT 方法无法将 JSON 转换为参数

转载 作者:行者123 更新时间:2023-11-28 21:33:42 25 4
gpt4 key购买 nike

我目前使用的是 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 没有被转换成正确的参数,这就是为什么我得到一个意外的 nil。

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

最佳答案

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

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

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

内容类型也可能是不必要的。

关于ruby-on-rails-3 - Rack::Test 使用 JSON 的 PUT 方法无法将 JSON 转换为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9009392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com