Sinatra Series 1: Basic Plumbing

Intro

Mission

  • Implementing a simple service in Sinatra
  • Service = Web Service = Web API
  • It will offer CRUD operations on a database
  • It will use Sinatra and ActiveRecord

Key technologies, standards, libraries, etc.

  • Like Rails, developing Sinatra apps involves many other pioeves of technology
  • Some of it is very reminiscent of Rails
  • Some is new.
    • Ruby
    • Sinatra
    • ActiveRecord
    • Erb
    • Postgres
    • JSON
    • Minitest

Setting Up Sinatra

  • Make sure you have the following installed:
    • rbenv 1.1+
    • ruby 2.6
    • git 2+
    • postgres
  • Unlike Rails, Sinatra does not dictate a directory structure
  • I have found the following to work well
  • The reason it looks a tiny bit like Rails is because it accomodates ActiveRecord most easily that way
/config
  database.yml
/db
  /migrate
    ...migration files
  schema.rb (generated)
/views
  ...erb files
/test
  ... test files
/models
  ... activerecord model files
config.ru
Gemfile
app.rb
Rakefile

Key files

# Gemfile
source "https://rubygems.org"

gem "sinatra"
gem "activerecord"
gem "sinatra-activerecord"
gem "pg"
# Rakefile
require './app'
require 'sinatra/activerecord/rake'
# app.rb
require 'sinatra'
require 'byebug'

get '/' do
  "Hello Sinatra!"
end
# config.ru
require './app'
run Sinatra::Application
# database.yml, where we declare various DB
# settings and parameters
development:
  adapter: postgresql
  encoding: unicode
  database: sin_series_dev
  pool: 2

test:
  adapter: postgresql
  encoding: unicode
  database: sin_series_test
  pool: 2

production:
  adapter: postgresql
  encoding: unicode
  database: sin_series_prod
  pool: 2
  username: your_username
  password: your_password

Using Rack::Test to do TDD

  • Add gem rack-test to Gemfile, bundle
  • Notice that all your server does so far is to return hello sinatra when it receives a GET at root
  • Lets test that
  • We are going to be using Rack::Test with Minitest/Spec
# test/root_test.rb
ENV['APP_ENV'] = 'test'

require_relative '../app.rb'
require 'minitest/autorun'
require 'rack/test'

include Rack::Test::Methods

def app
  Sinatra::Application
end

describe 'The HelloWorld App' do

  it "says hello" do
    get '/'
    last_response.ok?
    last_response.body.must_equal 'Hello Sinatra!'
  end
end
  • When you run this program (ruby test/root_test.rb) it will run the test and it should succeed
  • This is the basic pattern we will use for testing.

Continues