-
-
Save ihsw/52f15b54d66d8189ef64 to your computer and use it in GitHub Desktop.
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
# posts_routes.rb | |
require 'sinatra/base' | |
require 'json' | |
require 'active_record' | |
class Post < ActiveRecord::Base | |
end | |
class PostsRoutes < Sinatra::Base | |
enable :logging, :dump_errors, :raise_errors | |
post '/posts' do | |
request_body = JSON.parse request.body.read | |
post = Post.create(body: request_body['body']) | |
post.to_json | |
end | |
get '/post/:id' do | |
Post.find(params['id']).to_json | |
end | |
delete '/post/:id' do | |
Post.destroy(params['id']) | |
end | |
put '/post/:id' do | |
request_body = JSON.parse request.body.read | |
post = Post.find(params['id']) | |
post.update(body: request_body['body']) | |
post.to_json | |
end | |
end | |
# server_test.rb | |
require 'minitest/autorun' | |
require 'rack/test' | |
require 'json' | |
require_relative '../lib/server' | |
require_relative './test_helper' | |
class ServerTest < MiniTest::Test | |
include Rack::Test::Methods | |
include TestHelper::Methods | |
def app | |
Server | |
end | |
def test_hello_world | |
get '/' | |
assert last_response.ok? | |
assert_equal 'Hello, world!', last_response.body | |
end | |
def test_ping | |
get '/ping' | |
assert last_response.ok? | |
assert_equal 'Pong', last_response.body | |
end | |
def test_reflection | |
body = { greeting: 'Hello, world!' } | |
response_body = _test_post_json '/reflection', body.to_json | |
assert_equal body[:greeting], response_body['greeting'] | |
end | |
def test_post_create | |
body = { body: 'Hello, world!' } | |
_create_post body | |
end | |
def test_post_get | |
# creating the post | |
body = { body: 'Hello, world!' } | |
create_response_body = _create_post body | |
# fetching it | |
id = create_response_body['id'] | |
get "/post/#{id}" | |
assert last_response.ok? | |
get_response_body = JSON.parse last_response.body | |
assert_equal create_response_body['body'], get_response_body['body'] | |
end | |
def test_post_delete | |
# creating the post | |
body = { body: 'Hello, world!' } | |
create_response_body = _create_post body | |
# deleting it | |
id = create_response_body['id'] | |
delete "/post/#{id}" | |
assert last_response.ok? | |
end | |
def test_post_put | |
# creating the post | |
create_body = { body: 'Hello, world!' } | |
create_response_body = _create_post create_body | |
# updating it | |
id = create_response_body['id'] | |
url = "/post/#{id}" | |
put_body = { body: 'Jello, world!' } | |
put url, put_body | |
assert last_response.ok?, "PUT #{url} was not 200: #{last_response.status}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment