Last active
August 29, 2015 14:00
-
-
Save JoshCheek/11058136 to your computer and use it in GitHub Desktop.
How to test a client for a backend app. Creates a simple app, simple client, consumes it with rack-test, starts it up on a server, consumes it with restclient.
This file contains hidden or 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
# backend app | |
require 'sinatra/base' | |
require 'json' | |
class UsersController < Sinatra::Base | |
get '/users/:id' do | |
JSON.dump id: params[:id].to_i, name: "Josh" | |
end | |
end | |
# a client to consume the backend app | |
require 'json' | |
class UsersClient | |
User = Struct.new :id, :name | |
def initialize(attributes) | |
@the_internetz = attributes.fetch :the_internetz | |
@base_url = attributes.fetch :base_url | |
end | |
def find(id) | |
response = @the_internetz.get @base_url + "/users/#{id}" | |
user_attributes = JSON.parse response.body | |
User.new user_attributes['id'], user_attributes['name'] | |
end | |
end | |
# test the client without needing to start a server | |
require 'rack/test' | |
test_client = UsersClient.new the_internetz: Rack::Test::Session.new(UsersController), | |
base_url: '' | |
user = test_client.find(12) | |
user.id # => 12 | |
user.name # => "Josh" | |
# use the client for real | |
require 'restclient' | |
require 'webrick' | |
server_thread = Thread.new do | |
Rack::Server.start app: UsersController, Port: 8080, server: 'webrick', Logger: WEBrick::Log.new($stdout) | |
end | |
sleep 2 # let the server start | |
real_client = UsersClient.new the_internetz: RestClient, | |
base_url: 'http://localhost:8080' | |
user = real_client.find(12) | |
user.id # => 12 | |
user.name # => "Josh" | |
server_thread.kill | |
# >> [2014-04-18 14:40:13] INFO WEBrick 1.3.1 | |
# >> [2014-04-18 14:40:13] INFO ruby 2.1.1 (2014-02-24) [x86_64-darwin13.0] | |
# >> [2014-04-18 14:40:13] INFO WEBrick::HTTPServer#start: pid=28022 port=8080 | |
# >> [2014-04-18 14:40:15] INFO going to shutdown ... | |
# !> localhost - - [18/Apr/2014:14:40:15 MDT] "GET /users/12 HTTP/1.1" 200 23 | |
# !> - -> /users/12 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
we used the same approach for a few projects, check out: https://github.com/jsl/shamrock