Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@benhamill
Created November 2, 2013 04:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benhamill/7275642 to your computer and use it in GitHub Desktop.
Save benhamill/7275642 to your computer and use it in GitHub Desktop.
Just testing out ideas from this blog post: https://brandur.org/service-stubs
require 'webmock'
require 'sinatra/base'
require 'multi_json'
require 'pry'
require 'faraday'
WebMock.disable_net_connect!
class HalSinatra < Sinatra::Base
configure do
mime_type :hal, 'application/hal+json'
end
before do
content_type :hal
end
after do
body MultiJson.dump(body) if content_type == 'application/hal+json'
end
end
class Stub < HalSinatra
get '/' do
{
_links: {
self: { href: '/' },
},
}
end
end
def stub_service(uri, stub, &block)
uri = URI.parse(uri)
port = uri.port != uri.default_port ? ":#{uri.port}" : ""
stub = block ? Sinatra.new(stub, &block) : stub
WebMock.stub_request(
:any,
%r{^#{uri.scheme}://(.*:.*@)?#{uri.host}#{port}/.*$}
).to_rack(stub)
end
uri = "http://example.com"
f = Faraday.new(uri)
stub_service(uri, Stub) do
get '/d' do
content_type :html
"d"
end
end
f.get('/') #=> 200, HAL document
f.get('/d') #=> 200, 'd'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment