Create a Gemfile
source 'https://rubygems.org'
gem 'sinatra'
gem 'json'
Run
bundle install
Create a ruby file. ie) cocktail_api.rb
require 'sinatra'
require 'json'
get '/' do
content_type :json
{ message: 'Hello World' }.to_json
end
Run the app
ruby cocktail_api.rb
Add RSpec to you Gemfile
group :test do
gem 'rspec'
gem 'rack-test'
end
Run
bundle install
Create a 'spec' directory and create two files: spec_helper.rb
and cocktail_api.rb
spec_helper.rb
require 'sinatra'
require 'rspec'
require 'rack/test'
ENV['RACK_ENV'] = 'test'
cocktail_api_spec.rb
require 'spec_helper'
require_relative '../cocktail_api'
describe 'Cocktail API' do
include Rack::Test::Methods
def app
Sinatra::Application.new
end
describe 'root path' do
before do
get '/'
end
it 'should be successful' do
expect(last_response).to be_ok
end
it 'should be a json response' do
expect(last_response.content_type).to eq('application/json')
end
it 'should return a hello world message' do
response_data = JSON.parse(last_response.body)
expect(response_data['message']).to eq('Hello World')
end
end
end
Run tests with
rspec
And/or create a Rakefile
require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new :specs do |task|
task.pattern = Dir['spec/**/*_spec.rb']
end
task :default => ['specs']
and run
rake
Create a config.ru file
require './app'
run Sinatra::Application
Then you can use rack to launch the app with
rackup
This will be required to deploy the app to Heroku.
If this is the first time you're using Heroku sign up for an account and then install the Heroku Toolkit from here:
https://devcenter.heroku.com/articles/getting-started-with-ruby#set-up
Once it's installed run
heroku login
heroku keys:add
Now Heroku is setup we can create an Heroku app for our project
heroku create
git push heroku master
Done! :-)