Skip to content

Instantly share code, notes, and snippets.

@jagdeepsingh
Last active May 18, 2017 07:58
Show Gist options
  • Save jagdeepsingh/ea4b14ebec1be8f11378e83d77f3fdfd to your computer and use it in GitHub Desktop.
Save jagdeepsingh/ea4b14ebec1be8f11378e83d77f3fdfd to your computer and use it in GitHub Desktop.
WebMock- Library for stubbing and setting expectations on HTTP requests in Ruby

WebMock

Stub a request

Match request body and headers in stub.

let!(:stub_api_request) { stub_request(:post, 'http://api-host.com/path/') }

Stub with params as a query string.

let!(:stub_api_request) {
  stub_request(:post, 'http://api-host.com/path/').
    with(body: 'CardNumber=411111111111&ExpiryYear=2017&ExpiryMonth=11&Cvv=123')
}

Stub with params as a Hash.

let!(:stub_api_request) {
  stub_request(:post, 'http://api-host.com/path/').
    with(body: { foo: 1, bar: 2 }, headers: request_headers)
}

Stub with request headers matching partially or fully.

let!(:stub_api_request) {
  stub_request(:post, 'http://api-host.com/path/').
    with(body: request_body,
         headers: { 'Accept' => '*/*',
                    'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
                    'User-Agent' => 'Ruby' })
}

Stub with a JSON response.

let!(:stub_api_request) {
  stub_request(:post, 'http://api-host.com/path/').
    to_return(body: 'Baz=3&Waq=4')
}

Return an object in response.

let(:charge) { Stripe::Charge.new(id: 'ch_12345678') }
let!(:stub_api_request) {
  stub_request(:post, 'http://api-host.com/path/').
    to_return(body: charge.to_json)
}

Stub with a Hash in response

let!(:stub_api_request) {
  stub_request(:post, 'http://api-host.com/path/').
    to_return(body: { foo: 1, bar: 2 }.to_json,
              headers: { 'Content-Type' => 'application/json' })
}

Set expectation

let!(:stub_api_request) { stub_request(:post, 'http://api-host.com/path/') }
before { make_purchase(credit_card_details) }
it { expect(stub_api_request).to have_been_requested }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment