Created
November 2, 2013 04:47
-
-
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
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
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