Last active

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

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.

View testing_a_client_for_a_backend_app.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
# 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

we used the same approach for a few projects, check out: https://github.com/jsl/shamrock

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.