Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...)

like image 371
user480826 Avatar asked Oct 19 '10 18:10

user480826


People also ask

How do I run an RSpec test?

Running tests by their file or directory names is the most familiar way to run tests with RSpec. RSpec can take a file name or directory name and run the file or the contents of the directory. So you can do: rspec spec/jobs to run the tests found in the jobs directory.

What is Ajax in testing?

AJAX (Asynchronous JavaScript and XML) is a group of interrelated Web development techniques that are used on the client-side (browser) to create interactive Web applications.

What are RSpec tests?

RSpec is a testing tool for Ruby, created for behavior-driven development (BDD). It is the most frequently used testing library for Ruby in production applications. Even though it has a very rich and powerful DSL (domain-specific language), at its core it is a simple tool which you can start using rather quickly.


2 Answers

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.

like image 120
Robert Speicher Avatar answered Sep 28 '22 07:09

Robert Speicher


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 
like image 25
odlp Avatar answered Sep 28 '22 08:09

odlp