Sinatra ActiveRecord Mock Server

So you’ve built your awesome shiny new RESTful Rails app. You’ve been developing the client and find it pretty tough to unit test it against your service. The problem is that data on your service persists causing inconsistent test results. The solution is to usually mock requests on the client which can be sometimes difficult. When that’s the case, I’ve found it easier to mock the service instead using Sinatra — a light-weight web server. This easy-to-setup server can leverage your existing ActiveRecord models using a temporary in-memory database enabling you to mock requests to responses consistently in any manner required.

/MyRailsApp/spec/Gemfile:

source 'http://rubygems.org'
gem 'sinatra'
gem 'sinatra-activerecord'
gem 'sqlite3'
gem 'require_all'

/MyRailsApp/spec/mock-server.rb:

require 'sinatra'
require 'sinatra/activerecord'
require 'require_all'

# Require ActiveRecord models
require_all '../app/models/*.rb'

# Use UTC timezone
Time.zone = "UTC"
ActiveRecord::Base.default_timezone = :utc

# Disable Concurrency
set :lock, true

before do
  ActiveRecord::Base.logger.level = Logger::ERROR

  # Setup in-memory Database
  ActiveRecord::Base.establish_connection({:adapter => 'sqlite3', :database => ':memory:'})
  ActiveRecord::Migration.verbose = false
  ActiveRecord::Migrator.up('../db/migrate')
  ActiveRecord::Base.logger.level = Logger::DEBUG

  # Any additional setup
end

after do
  #nothing yet
end

post '/' do
  "Hello World!"
end

# Example POST User
post '/users' do
  post = JSON.parse(request.body.read)
  puts post.inspect

  begin
    raise if User.find_by_id(post["user"]["id"])
    @user = User.create!(post["user"])
    content_type 'application/json'
    status 201
    response = @user.to_json
    puts response
    response
  rescue
    status 400
  end
end

Install Gems:

$ cd /MyRailsApp/spec
$ bundle install

Start Server:

$ ruby -rubygems mock-server.rb

Check out the gist:
https://gist.github.com/1439361

Advertisements