Skip to content

Instantly share code, notes, and snippets.

@yevgenko
Created March 2, 2017 22:33
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 yevgenko/41a794b9bc034e133df127b91c93f77f to your computer and use it in GitHub Desktop.
Save yevgenko/41a794b9bc034e133df127b91c93f77f to your computer and use it in GitHub Desktop.
Example of using pact with webmock, i.e. to proxy connection via Rack application to mock service without changing base_url in client library
require 'httparty'
require_relative 'pact_helper'
require 'webmock/rspec'
require 'byebug'
require 'rack/proxy'
WebMock.disable_net_connect!(allow_localhost: true)
class Alligator
attr_reader :name
def initialize name
@name = name
end
def == other
other.is_a?(Alligator) && other.name == name
end
end
class AnimalServiceClient
include HTTParty
base_uri 'http://animal-service.com'
def get_alligator
name = JSON.parse(self.class.get("/alligator").body)['name']
Alligator.new(name)
end
end
class AnimalServiceRackApp < Rack::Proxy
def rewrite_env(env)
env['HTTP_HOST'] = 'localhost'
env['SERVER_PORT'] = 1234
env
end
end
describe AnimalServiceClient, :pact => true do
before do
# Configure your client to point to the stub service on localhost using the port you have specified
# AnimalServiceClient.base_uri 'localhost:1234'
stub_request(:any, /animal-service.com/).to_rack(AnimalServiceRackApp.new(nil, streaming: false))
end
subject { AnimalServiceClient.new }
describe "get_alligator" do
before do
animal_service.given("an alligator exists").
upon_receiving("a request for an alligator").
with(method: :get, path: '/alligator', query: '').
will_respond_with(
status: 200,
headers: {'Content-Type' => 'application/json'},
body: {name: 'Betty'} )
end
it "returns a alligator" do
expect(subject.get_alligator).to eq(Alligator.new('Betty'))
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment