如何在rails 3功能测试中发布JSON数据

cyf*_*cyf 15 json ruby-on-rails functional-testing

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

搜索一段时间后,我找到以下curl用于发布JSON数据的代码:

curl -H "Content-Type:application/json" -H "Accept:application/json" \
    -d '{ "foo" : "bar" }' localhost:3000/api/new
Run Code Online (Sandbox Code Playgroud)

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

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

这是我尝试过的.我找到了xhrin 的实现action_controller/test_case.rb,并尝试添加jhr方法只需更改'Conetent-Type'和'HTTP_ACCEPT'.(已添加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
Run Code Online (Sandbox Code Playgroud)

我以同样的方式使用xhr它,但它不起作用.我检查了@response物体并看到了尸体" ".

我还在Stack Overflow上找到了一个类似的问题,但它是针对rails 2的,并且发布原始数据的答案在rails 3中不起作用.

Pau*_*ell 18

从Rails 5开始,执行此操作的方法是:

post new_widget_url, as: :json, params: { foo: "bar" }
Run Code Online (Sandbox Code Playgroud)

这也将Content-type正确设置标题(to application/json).


Seb*_*mba 10

我发现这正是我想要的 - 将JSON发布到控制器的动作中.

post :create, {:format => 'json', :user => { :email => "test@test.com", :password => "foobar"}}
Run Code Online (Sandbox Code Playgroud)


Gri*_*mmo 9

只需指定适当的内容类型:

post :index, '{"foo":"bar", "bool":true}', "CONTENT_TYPE" => 'application/json'
Run Code Online (Sandbox Code Playgroud)

Json数据应该作为字符串,而不是哈希.查看运行测试的堆栈跟踪,您可以获得对请求准备的更多控制:ActionDispatch :: Integration :: RequestHelpers.post => ActionDispatch :: Integration :: Session.process => Rack :: Test :: Session.env_for

指定:格式不起作用,因为请求变为'application/x-www-form-urlencoded'并且json未正确解析处理请求正文.

  • 直接冒充字符串将得到以下错误``NoMethodError:undefined method`nolceize_keys'for"{\"foo \":\"bar \"}":String`` (7认同)