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?
 
                        
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 ValidationandjQuery Formsplugins on the client end.jQuery Formsdoesn'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.Of course this is specific to the way the
jQuery Formsplugin works and not at all how one would normally go about testing the POSTing of JSON data via AJAX. I hope this helps others.