Thursday, November 24, 2011

Adding rspec to sinatra

In the previous post I showed how to deploy a sample sinatra app on Cloud Foundry using rake, and now I'm going to add rspec tests to the app.

The first step is to add the rspec gem to your Gemfile and run bundle
source ""

gem 'sinatra'

group :test do
  gem 'rspec'
Next you need to create the spec directory and add the spec_helper.rb file
require File.join(File.dirname(__FILE__), '..', 'app.rb')

require 'sinatra'
require 'rack/test'

# setup test environment
set :environment, :test
set :run, false
set :raise_errors, true
set :logging, false

def app

RSpec.configure do |config|
  config.include Rack::Test::Methods
This is for a classic style sinatra app, if you are using a modular app, you need to make some slight modifications for it to work. I'll show how to do that in a later post.

And finally you are ready to create the spec file that corresponds to the app.rb
require 'spec_helper'

describe "Sinatra App" do

  it "should respond to GET" do
    get '/'
    last_response.should be_ok
    last_response.body.should match(/It works!/)

I usually don't use rspec for integration tests, for that I use cucumber. I normally use rspec for unit testing, but since this is a sample app and I don't have any models to test, I included this test for completeness sake. I'll write another blog post how to add cucumber tests to this sample sinatra app later.
To make life easier, I've added a rake task to run the rspec tests
require 'rspec/core/rake_task'

desc "run specs"
And then I've updated the deployment task to require the rspec task, so we can't update the application unless it passes all tests.
namespace :vmc do
  desc "update cloud foundry deployment"
  task :update => [:bundle, :spec] do
    sh "vmc update #{VMC_APP_NAME}"
I've created a github repository for this app to make it easier for you to use it as a template.


  1. I think it's wrong to show people how "You can do something". Why?
    ANS: Because that is not how you "Martin" normally do it. It is most helpful to show people how you actually do it because that is the way it works for you.

    In this case I would show people how you create database backed Modular Sinatra Apps.

    And the most important bit is How you incorporate Cucumber, Why you prefer it for the Purpose you use it. The same for RSpec, MiniTest etc.

    Because being wishy-washy doesn't really show understanding but doubt. There is a lot of ways to do it, but show us how and why you do it your way.



    1. Nelson,

      unfortunately I can't always publish how I do things in an existing project, as I'm not allowed to make it public. I can write a post on which testing framework I prefer and why, but this post sprung out of the lack of documentation on how to get rspec & sinatra playing together.


  2. I found the post useful as I get started writing tests for sinatra. Thanks!