How do you test an AJAX request with RSpec/RoR?

Ruby on-RailsAjaxTestingRspecmocha.js

Ruby on-Rails Problem Overview


I'm fairly new to RoR and recently started learning BDD/Rspec for testing my application. I've been looking for a way to spec an AJAX request, but so far I haven't found much documentation on this at all.

Anyone know how to do this? I'm using rails 2.3.8, rspec 1.3.0 and mocha 0.9.8 for my stubs (which I'm also in the process of learning...)

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

If you're talking about testing it inside your controller specs, where you normally call

get :index

to make an HTTP request to the index action, you would instead call

xhr :get, :index

to make an XmlHttpRequest (AJAX) request to the index action using GET.

Solution 2 - Ruby on-Rails

Rails 5 / 6

Since Rails 5.0 (with RSpec 3.X), try setting xhr: true like this:

get :index, xhr: true

Background

Here's the relevant code in the ActionController::TestCase. Setting the xhr flag ends up adding the following headers:

if xhr
  @request.set_header "HTTP_X_REQUESTED_WITH", "XMLHttpRequest"
  @request.fetch_header("HTTP_ACCEPT") do |k|
    @request.set_header k, [Mime[:js], Mime[:html], Mime[:xml], "text/xml", "*/*"].join(", ")
  end
end

Solution 3 - Ruby on-Rails

Syntax changed a bit for Rails 5 and rspec > 3.1(i believe)

for POST requests:

post :create, xhr: true, params: { polls: { question: 'some' } }

you now need explicitely set params

for GET requests:

get :action, xhr: true, params: { id: 10 }

for rails 4 and rspec <= 3.1

xhr post :create, { polls: { question: 'some' } }

GET requests:

xhr get :show, id: 10

Solution 4 - Ruby on-Rails

Here is a full example:

get "/events", xhr: true, params: { direction: "past" }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser480826View Question on Stackoverflow
Solution 1 - Ruby on-RailsRobert SpeicherView Answer on Stackoverflow
Solution 2 - Ruby on-RailsodlpView Answer on Stackoverflow
Solution 3 - Ruby on-Railsuser1136228View Answer on Stackoverflow
Solution 4 - Ruby on-RailsDorianView Answer on Stackoverflow