RSpec an XHR Request
Looking at the RSpec docs it was not so obvious to me how you handled a XHR request in your controller specs, so here it is:
1 |
xhr :get, :index |
Simple of course, just passing in the HTTP request type and the action you want requested to the xhr method. Still it is slightly confusing compared to the syntax for a regular get request which has it’s own get method:
1 |
get :index
|
For interests sake here is the code I was testing, it is an improved way of doing AJAX pagination with rails and jQuery than what is suggested here because using respond_to request.js when setting the request header to ‘text/javascript’ in jQuery like so doesn’t work reliably with all browsers.
The controller:
1 2 3 4 |
def index @users = User.paginate(:order => 'name', :page => params[:page]) render(:partial => 'table', :layout => false) if request.xhr? # Otherwise render index.haml end |
And the spec for the xhr part:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
describe "handling XHR /admin/users (for table AJAX pagination)" do def do_xhr_get xhr :get, :index end it "should be successful" do do_xhr_get response.should be_success end it "should render table partial template" do do_xhr_get response.should render_template('_table') end end |