Skip to content

Instantly share code, notes, and snippets.

@ggorlen
Last active March 27, 2022 02:24
Show Gist options
  • Select an option

  • Save ggorlen/8ffa362cea728b76ea80f82c033ee979 to your computer and use it in GitHub Desktop.

Select an option

Save ggorlen/8ffa362cea728b76ea80f82c033ee979 to your computer and use it in GitHub Desktop.
Sinatra + RSpec basic testing
require 'json'
require 'sequel'
require 'sinatra/base'
class SinatraApp < Sinatra::Base
# https://stackoverflow.com/a/20726197/6243352
def initialize(app = nil, db)
super(app)
@db = db
end
#configure do
# DB = Sequel.sqlite
# DB.create_table :notes do
# primary_key :id
# String :content
# end
#end
get '/api/notes/:id' do
note = @db[:notes].first(:id => params[:id])
if note.nil?
404
else
note.to_json
end
end
post '/api/notes' do
body = JSON.parse(request.body.read)
if !body.has_key? "content"
422
elsif @db[:notes].insert(:content => body["content"]).nil?
500
else
200
end
end
end
require 'json'
require 'rack/test'
require 'sinatra_app'
def parse_json?(json)
JSON.parse(json)
rescue JSON::ParserError => e
nil
end
describe 'Sinatra App' do
include Rack::Test::Methods
let(:db) {Sequel.sqlite}
let(:app) {SinatraApp.new(db)}
before do
db.create_table :notes do
primary_key :id
String :content
end
end
after do
db.drop_table :notes
end
it 'works on POST and GET /api/notes/' do
post '/api/notes', {:content => 'hello world'}.to_json
expect(last_response.ok?).to be true
expect(last_response.status).to eq 200
get '/api/notes/1'
body = parse_json?(last_response.body)
expect(body).to be_instance_of Hash
expect(body).to eq({'id' => 1, 'content' => 'hello world'})
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment