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

I am new to RoR and recently started learning BDD / Rspec to test my application. I was looking for a way to specify an AJAX request, but so far I have not found much documentation about this.

Does anyone know how to do this? I use rails 2.3.8, rspec 1.3.0 and mocha 0.9.8 for my stubs (which I also study ...)

+53
ajax ruby-on-rails testing mocha rspec
Oct 19 2018-10-18
source share
3 answers

If you are talking about testing it in your controller specifications, where you usually call

get :index 

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

 xhr :get, :index 

to execute an XmlHttpRequest (AJAX) request for an index action using GET.

+106
Oct 19 '10 at 18:27
source share

Rails 5/6

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

 get :index, xhr: true 

Background

Here is the corresponding code in ActionController :: TestCase . Setting the xhr flag adds 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 
+26
Jun 21 '17 at 15:15
source share

The syntax has changed a bit for Rails 5 and rspec> 3.1 (I believe)

for POST requests:

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

Now you need to install params exactly

for GET requests:

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

for rails 4 and rspec <= 3.1

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

GET inquiries:

 xhr get :show, id: 10 
+4
Feb 16 '18 at 9:23
source share



All Articles