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...)
If you're talking about testing it inside your controller specs, where you normally call
to make an HTTP request to the index action, you would instead call
to make an XmlHttpRequest (AJAX) request to the index action using GET.
Syntax changed a bit for Rails 5 and rspec > 3.1(i believe)
for POST requests:
you now need explicitely set
params
for GET requests:
for rails 4 and rspec <= 3.1
GET requests:
Rails 5
Since Rails 5.0 (with RSpec 3.X), try setting
xhr: true
like this:Background
Here's the relevant code in the ActionController::TestCase. Setting the
xhr
flag ends up adding the following headers: