Sinatra Basics : Cleanup


To clean up the code from previous article.


Step 1

In the Gemfile, we only add gems to the required environment.

source ''

gem 'sinatra'

group :test, :development do
  gem "rspec"

group :test do
  gem "rack-test", require: "rack/test"

Step 2

require_relative 'hello_world'

run HelloWorld

Instead of hard coding '.', we now use require_relative.

Step 3

In spec/hello_world_spec.rb:

require_relative 'spec_helper.rb'
require_relative '../hello_world.rb'

RSpec.describe HelloWorld  do

  it 'should greet' do
    get '/'

    expect(last_response).to be_ok
    expect(last_response.body).to eq('Hello, world!')

Step 4

In hello_world.rb

ENV['RACK_ENV'] ||= 'development'

require 'bundler'
Bundler.require :default, ENV['RACK_ENV'].to_sym

class HelloWorld < Sinatra::Base
  get '/' do
    'Hello, world!'

Intead of require 'sinatra', we are using bundler to require the gems that is necessary for the given environment.

Step 5

Add .rspec file with:

--format documentation

Step 6

Run the tests.

$bundle exec rspec

Step 7

Run the application.


Step 8

Browse to localhost:9292.


In this article, we cleaned up the code by grouping gems in the appropriate environment and using Bundler to require the gems needed in a given environment. We also used default values to make the output show in color with formatted documentation when we run rspec.


Sinatra Best Practices
Sinatra Best Practices
Sinatra Explained

Related Articles

Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.