如何在 Rails 功能测试中发送原始帖子数据? [英] How to send raw post data in a Rails functional test?
问题描述
我希望将原始发布数据(例如未参数化的 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 #
错误.
but this gives me a NoMethodError: undefined method `symbolize_keys' for #<String:0x00000102cb6080>
error.
在 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
如果你看看 源代码 你会看到 raw_post
只是包装了 request.body.read
并检查了这个 RAW_POST_DATA
在request
env 哈希.
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屋!