Testing Sinatra With Rack-test

A common problem when starting out with Sinatra and trying to exercise what you’ve built with rack-test is that by default, Sinatra will swallow your errors and spit them out as a big HTML page in the response body. Trying to debug your tests by inspecting an HTML backtrace from last_response.body is a harrowing experience (take it from someone who’s tried).

The solution is to tell Sinatra to raise errors back to you instead of burying them in HTML. Here’s the proper combination of options to accomplish that:

set :raise_errors, true
set :show_exceptions, false

Here’s a more complete example:

# app.rb
class App < Sinatra::Base
  configure do
    set :raise_errors, true
    set :show_exceptions, false
  end

  get "/" do
    raise "error!"
  end
end
# app_test.rb
describe App do
  include Rack::Test::Methods

  it "shows an error" do
    get "/"
  end
end

Posted on December 29, 2012 from Calgary

About

My name is Brandur. I'm a polyglot software engineer and part-time designer working at Heroku in San Francisco, California. I'm a Canadian expat. My name is Icelandic. Drop me a line at brandur@mutelight.org.

Aside from technology, I'm interested in energy and how it relates to our society, travel, longboarding, muay thai, symphonic metal, and the guitar.

If you liked this article, consider finding me on Twitter.