Sinatra, DataMapper and RSpec 2

Getting up and running with Sinatra, DataMapper and the new RSpec.

Earlier today I was trying to get up to speed with Sinatra, DataMapper and RSpec. There is a great step by step tutorial for Sinatra and RSpec 1 if you need that, but I want to play with the shiny new stuff, so here we go.


You don't have to use Bundler but it will make your (and your collaborators) gem dependencies so much easier. Start with creating a Gemfile in your project's root folder and add the gems you need.

source :rubygems

gem "sinatra"
gem "dm-sqlite-adapter"
gem "datamapper"

group :test do
  gem "rspec"
  gem "rack-test"

Now run bundle install (check the Bundler docs for installation instructions). This will install the gems specified above and create a Gemfile.lock file in the same directory.


Let's configure RSpec. Create a spec directory in your project's root folder with a spec_helper.rb and myapp_spec.rb file (replace myapp with your app's name). Now, add the following to the spec_helper.rb file:

require File.join(File.dirname(__FILE__), '..', 'myapp.rb')

require 'rubygems'
require 'sinatra'
require 'rack/test'
require 'rspec'

set :environment, :test

Rspec.configure do |config|
  config.before(:each) { DataMapper.auto_migrate! }

The first line requires your Sinatra application (again, rename it with your application). The following lines require the stuff we need to run the tests and after that, we set the environment. The last 3 lines reset the database before each test to make sure our tests don't influence one another.

Let's move on to the myapp_spec.rb:

require File.dirname(__FILE__) + '/spec_helper'

describe 'MyApp' do
  include Rack::Test::Methods

  def app

  it 'should run a simple test' do
    get '/'
    last_response.status.should == 200

This is where your tests go, how these work is out of scope for this tutorial. You can now run the test with RACK_ENV=test rspec . (that's a dot at the end).


If you don't specify another database it will use the same database for each environment. The data will be cleared each time. You can use the following snippet to use different database configurations per environment. Add this to your main application file.

DataMapper.setup(:default, "postgres://localhost/myapp")
configure :test do
  DataMapper.setup(:default, "sqlite::memory:")

That's all, happy testing!