本文介绍了测试AJAX POST使用机架::测试的 - 如何传递数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用机架::测试来测试我的应用程序,需要测试发布通过AJAX数据。

I'm using Rack::Test to test my app and need to test the posting of data via AJAX.

我的测试是这样的:

describe 'POST /user/' do
  include Rack::Test::Methods
  it 'must allow user registration with valid information' do
    post '/user', {
      username: 'test_reg',
      password: 'test_pass',
      email: '[email protected]'
    }.to_json, {"CONTENT_TYPE" => 'application/json', "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest"}
    last_response.must_be :ok?
    last_response.body.must_match 'test_reg has been saved'
  end
end

但在服务器端它不接收发布的数据。

But at the server end it's not receiving the POSTed data.

我也尝试只是传递params哈希表没有 to_json 但是这并没有区别。

I also tried just passing in the params hash without the to_json but that made no difference.

不知道如何做到这一点?

Any idea how to do this?

推荐答案

好了,所以我的解决办法是有点怪异而具体到我触发首先我的JSON请求,即使用方式的jQuery验证 jQuery的形式上的客户端插件。 jQuery的形式不捆绑表单字段成字符串化的哈希我预料,但通过AJAX,但作为一个典型的URI发送表单字段连接codeD PARAMS串。因此,通过改变我的测试下,现在工作得很好。

Okay so my solution is a little weird and specific to the way I am triggering my JSON request in the first place, namely using jQuery Validation and jQuery Forms plugins on the client end. jQuery Forms doesn't bundle the form fields into a stringified Hash as I'd expected, but sends the form fields via AJAX but as a classic URI encoded params string. So by changing my test to the following, it now works fine.

describe 'POST /user/' do
  include Rack::Test::Methods
  it 'must allow user registration with valid information' do
    fields = {
      username: 'test_reg',
      password: 'test_pass',
      email: '[email protected]'
    }
    post '/user', fields, {"HTTP_X_REQUESTED_WITH" => "XMLHttpRequest"}
    last_response.must_be :ok?
    last_response.body.must_match 'test_reg has been saved'
  end
end

当然,这是特定的方式 jQuery的形式插件的作品,而不是在所有的一个人如何通常会去通过AJAX测试的JSON数据的发布。我希望这可以帮助别人。

Of course this is specific to the way the jQuery Forms plugin works and not at all how one would normally go about testing the POSTing of JSON data via AJAX. I hope this helps others.

这篇关于测试AJAX POST使用机架::测试的 - 如何传递数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 14:16