如何在Rails功能测试中发送原始帖子数据? [英] How to send raw post data in a Rails functional test?

查看:135
本文介绍了如何在Rails功能测试中发送原始帖子数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将原始帖子数据(例如,未参数化的JSON)发送到我的一个控制器进行测试:

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

但这给了我一个NoMethodError: undefined method `symbolize_keys' for #<String:0x00000102cb6080>错误.

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

What is the correct way to send raw post data in ActionController::TestCase?

这是一些控制器代码:

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内定义以下方法:

In your test_helper.rb define the following method inside of 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方法一样使用它,但将原始文章正文作为第三个参数传递.

In your functional test, use it just like the post method but pass the raw post body as the third argument.

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

在使用

request.raw_post

代替

request.body.read

如果您查看

If you look at the source code you'll see that raw_post just wraps request.body.read with a check for this RAW_POST_DATA in the request env hash.

这篇关于如何在Rails功能测试中发送原始帖子数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆