Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
85 lines (60 sloc) 3.11 KB
layout: post
title: Sinatra, DataMapper and RSpec 2
date: 2010-10-18 21:39:54
updated: 2010-12-12 00:09:00
<div class="narrow-col">
<p>Earlier today I was trying to get up to speed with Sinatra, DataMapper and RSpec. There is a great <a href="" title="RSpec and Sinatra Quick Start">step by step tutorial</a> for Sinatra and RSpec 1 if you need that, but I want to play with the shiny new stuff, so here we go.</p>
<p>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.</p>
{% highlight ruby %}
source :rubygems
gem "sinatra"
gem "dm-sqlite-adapter"
gem "datamapper"
group :test do
gem "rspec"
gem "rack-test"
{% endhighlight %}
<p>Now run <em>bundle install</em> (check the <a href="" title="Bundler, dependency management for Ruby">Bundler docs</a> for installation instructions). This will install the gems specified above and create a Gemfile.lock file in the same directory.</p>
<p>Let's configure RSpec. Create a <em>spec</em> directory in your project's root folder with a <em>spec_helper.rb</em> and <em>myapp_spec.rb</em> file (replace myapp with your app's name). Now, add the following to the <em>spec_helper.rb</em> file:</p>
{% highlight ruby %}
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! }
{% endhighlight %}
<p>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.</p>
<p>Let's move on to the <em>myapp_spec.rb</em>:</p>
{% highlight ruby %}
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
{% endhighlight %}
<p>This is where your tests go, how these work is out of scope for this tutorial. You can now run the test with <em>RACK_ENV=test rspec .</em> (that's a dot at the end).</p>
<p>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.</p>
{% highlight ruby %}
DataMapper.setup(:default, "postgres://localhost/myapp")
configure :test do
DataMapper.setup(:default, "sqlite::memory:")
{% endhighlight %}
<p>That's all, happy testing everyone. :)</p>