I'm looking to send raw post data (e.g. unparamaterized JSON) to one of my controllers for testing:

class LegacyOrderUpdateControllerTest < ActionController::TestCase
  test "sending json" do
    post :index, '{"foo":"bar", "bool":true}'
  end
end

but this gives me a NoMethodError: undefined method `symbolize_keys' for #<String:0x00000102cb6080> error.

ActionController::TestCase分钟内发送原始帖子数据的正确方法是什么?

Here is some controller code:

def index
  post_data = request.body.read
  req = JSON.parse(post_data)
end

推荐答案

I ran across the same issue today and found a solution.

在您的test_helper.rb中,在ActiveSupport::TestCase中定义以下方法:

def raw_post(action, params, body)
  @request.env['RAW_POST_DATA'] = body
  response = post(action, params)
  @request.env.delete('RAW_POST_DATA')
  response
end

在您的功能测试中,可以像使用post方法一样使用它,但要将原始的POST正文作为第三个参数传递.

class LegacyOrderUpdateControllerTest < ActionController::TestCase
  test "sending json" do
    raw_post :index, {}, {:foo => "bar", :bool => true}.to_json
  end
end

我在Rails 2.3.4上使用以下命令读取原始POST正文时测试了这一点

request.raw_post

instead of

request.body.read

如果你看source code,你会发现raw_post只是在request env散列中用一个RAW_POST_DATA判断request.body.read.

Json相关问答推荐

在PowerShell中,如何获取数据对所在的JSON对象的名称

Postgres Select json数组并重新映射属性名称

褐煤面积图中的分选问题

如何在Swift中使用JSON编码器的泛型

重构JOLT代码以获得预期输出

Jolt:数组中两个字符串的连接

NoneType 对象的 Python 类型错误

使用 jq 获取所有嵌套键和值

PowerShell - 将 json 添加到文件内容

未知的META规范,无法验证.[规范v1.0.1]

使用 jq 将消息转换为数组

使用 @ResponseBody 自定义 HttpMessageConverter 来做 Json 事情

以 unicode 将 pandas DataFrame 写入 JSON

使用 gson 反序列化对象的特定 JSON 字段

数据包含连续问号时无法理解的 jQuery $.ajax() 行为

如何在 Rails 模型中验证字符串是否为 json

ASP.NET Core API 仅返回列表的第一个结果

使用 Codable 序列化为 JSON 时的 Swift 字符串转义

带有 Jackson 的不可变 Lombok 注释类

将 JSON 模式转换为 python 类