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...)
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.
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.
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.
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.
Since Rails 5.0 (with RSpec 3.X), try setting xhr: true
like this:
get :index, xhr: true
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With