eddorre

Using Rack-Test and RSpec to Test a RESTful API in Rails 2.3.x

I recently started writing a RESTful API using rack-test for an existing Rails 2.3.11 application, but I noticed the documentation didn’t really go into setting it up for a Rails 2.3 project.

Here are some simple steps to get it going.

In my spec helper file, I wrote the following module:


module ApiHelper
  require 'rack/test'
  include Rack::Test::Methods

  def app
    ActionController::Dispatcher.new
  end
end

Then I can use include the ApiHelper in all of my API specs and write code like:

  
require 'spec_helper'
include ApiHelper

describe 'API Authentication' do
  it "should return json errors with no token" do
    get '/api/tasks.json', :token => ''
    error = { :error => "Token is invalid." }
    last_response.body.should eql(error.to_json)
  end
end    
 

For more examples on building a RESTful API using RSpec, I highly recommend checking out Ryan Bigg’s Ticketee project for his forthcoming Rails book, Rails 3 in Action


Comments

Comments are closed

Comments are closed on this post. If you have something on your mind regarding this post, don't hesitate to drop me a line.