Sinatra Best Practices: Part Two

Travis Herrick ·

In Sinatra Best Practices: Part One we saw how to break up your Sinatra application into
smaller bite-size pieces. Today, we’re going to explore testing, which will also
compel us to address environment configuration.

We typically use Bundler to manage dependencies on our Ruby projects, which means we’ll use a Gemfile to handle that for us. This will also allow us to control which libraries are loaded in different environments. We don’t really want testing dependencies loaded in production, after all.

To get started, we need to add rspec and rack-test to our gem file:

Now we can leverage different environments to load only the gems we need.
We don’t really want RSpec loaded in production, after all, do we?

The first line sets the environment to development by default. After that, we
use Bundler to load only the gems for the appropriate environment.

We’re pretty big believers in having the default rake task run your full test
suite, so to that end, our rakefile looks something like this:

Now, a simple bundle exec rake will run our full test suite, which will yield
0 tests run at this point, so let’s fix that by adding some. We’ll start with
the spec_helper, which is not a requirement, per se, but makes things
quite clean when we get to constructing tests, as we’ll see in just a moment.

In our spec helper, we force the environment to be test and then load the app,
which will load the appropriate gems via bundler.

So let’s add a spec:

And there we have it. Our Sinatra app is loading only the gems necessary for
the environment and our testing infrastructure is in place.

If you missed it, be sure to check out Sinatra Best Practices: Part One, where we talked about how to structure your Sinatra application code.

Credits

This article was co-written by Travis Herrick and Erin Swenson-Healey.

You can see the functioning sample app (and the readmes) here.