Testing AJAX Requests in Ruby on Rails

August 30th, 2007 by Jack

In our applications, many of our controllers should only be interacted with via AJAX. This is easy enough to enforce in a controller, using the special verification filter:

class PostController < ApplicationController
verify :xhr => true, :render => { :text => "This action must be accessed using XMLHttpRequest." }
end

However, it took me a little while to figure out how to test this appropriately. The following functional test for the above controller will fail:

def test_edit
post :edit, :id => 1
assert_kind_of Post, assigns("post")
end

In order to simulate an AJAX request, you need to use the xhr method instead of the post method:

def test_edit
xhr :post, :edit, :id => 1
assert_kind_of Post, assigns("post")
end

Unfortunately, this technique doesn’t seem to be mentioned in the Guide to Testing the Rails.

Posted in ruby on rails |

One Response

  1. Jack Says:

    It’s clear we’re going to have to retool our blogging platform - WordPress is not a fan of ruby code!

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.