Created
December 6, 2011 18:44
-
-
Save panupan/1439361 to your computer and use it in GitHub Desktop.
Sinatra ActiveRecord Mock Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
source 'http://rubygems.org' | |
gem 'sinatra' | |
gem 'sinatra-activerecord' | |
gem 'sqlite3' | |
gem 'require_all' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
These instructions assume the files are put in your Rails application's spec folder.
Install gems:
$ cd spec
$ bundle install
Start server:
$ ruby -rubygems mock-server.rb