Written by: steve ross on July 7th 2008

Didja ever wonder how to send a particular HTTP header as part of your functional test or controller spec? Ever wonder who would care about something like that? Read this spec:

- PostsController receiving Ajax requests  
  - Should send the information back as JSON

Ok, spot quiz: How the heck do you emulate an Ajax call correctly from your rSpec code (and the answer is not "use post")?

Answer. You probably already guessed. Use the HTTP headers to inform Rails what you had in mind.

Here's a snippet:

  
describe PostsController, "receiving Ajax calls" do
  it "Should send the information back as JSON" do
    request.env['HTTP_ACCEPT'] = 'application/json, text/javascript, */*'
    request.env['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
    get :index, :id => 666
  end
end
  

See, my Ajax call happens using the GET method but it's still an Ajax request. Why? Because I said so. No, actually because the request was made using XmlHttpRequest.

I also get JSON back if I have a respond_to that responds to json.

This is a great way to make sure your controllers are responding the the protocol as you expect and that they are shipping back the desired data.