Testing an AJAX POST using Rack::Test - how to pass in data?

2.3k Views Asked by At

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

My test looks like:

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.

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

Any idea how to do this?

2

There are 2 best solutions below

3
On BEST ANSWER

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

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.

1
On

Your post endpoint must parse the posted JSON body itself, which I assume you already do. Can you post how your end point works, also the rack-test, rack,ruby and sinatra version numbers? Please mention also how you test whether the server's receiving anything -- namely test mockup may confuse your detection.

    post '/user' do
       json_data = JSON.parse(request.body.read.to_s)
       # or # json_data = JSON.parse(request.env["rack.input"].read)
       ...
    end