How do you test an AJAX request with RSpec/RoR?
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.
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(", ") endend
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