如何在Rails 3功能测试中发布JSON数据 [英] How to post JSON data in rails 3 functional test

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

问题描述

我计划在项目的请求和响应中都使用JSON数据,并且在测试中遇到一些问题.

I plan to use JSON data in both request and response in my project and having some problems in testing.

搜索了一会儿之后,我发现以下代码使用curl发布JSON数据:

After searching for a while, I find the following code which uses curl to post JSON data:

curl -H "Content-Type:application/json" -H "Accept:application/json" \
    -d '{ "foo" : "bar" }' localhost:3000/api/new

在控制器中,我可以轻松地使用params[:foo]来访问JSON数据.但是对于功能测试,我只找到postxhr(xml_http_request的别名).

In the controller I can access the JSON data simply using params[:foo] which is really easy. But for functional testing, I only find post and xhr (alias for xml_http_request).

如何在rails中编写功能测试以达到与使用curl相同的效果?还是应该以其他方式进行测试?

How can I write functional test in rails to achieve the same effect as using curl? Or should I do test in other ways?

这就是我尝试过的.我在action_controller/test_case.rb中找到了xhr的实现,并试图添加jhr方法,只是更改了'Conetent-Type'和'HTTP_ACCEPT'. (在test/test_helpers.rb中添加.)

Here's what I've tried. I find the implementation for xhr in action_controller/test_case.rb, and tried to add jhr method simply changing 'Conetent-Type' and 'HTTP_ACCEPT'. (Added in test/test_helpers.rb.)

def json_http_request(request_method, action, parameters = nil, session = nil, flash = nil)
  @request.env['Content-Type'] = 'Application/json'
  @request.env['HTTP_ACCEPT'] ||= [Mime::JSON, Mime::JS, Mime::HTML, Mime::XML, 'text/xml', Mime::ALL].join(', ')
  __send__(request_method, action, parameters, session, flash).tap do
    @request.env.delete 'Content-Type'
    @request.env.delete 'HTTP_ACCEPT'
  end
end
alias jhr :json_http_request

我以与xhr相同的方式使用了它,但是它不起作用.我检查了@response对象,发现主体是" ".

I used this in the same way as xhr, but it does not work. I inspected the @response object and sees the body is " ".

我还发现一个类似的问题在Stack Overflow上,但它适用于Rails 2,而发布原始数据的答案在Rails 3中不起作用.

I also find one similar question on Stack Overflow but it's for rails 2 and the answer for posting raw data does not work in rails 3.

推荐答案

从Rails 5开始,实现此目的的方法是:

As of Rails 5, the way to do this is:

post new_widget_url, as: :json, params: { foo: "bar" }

这还将正确设置Content-type标头(至application/json).

This will also set the Content-type header correctly (to application/json).

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

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