Webmock Adapter

This integration interfaces with webmock, a popular ruby gem for stubbing HTTP requests in tests.

Here’s how you can activate this integration:

# minitest
require "webmock"
require "httpx/adapters/webmock"
require "webmock/minitest"

class Mytest < Minitest::Test
  def setup
    stub_http_request(:get, "https://www.google.com").and_return(status: 200, body: "here's google")
  end

  def test_httpx_call
    response = HTTPX.get("https://www.google.com")
    assert response.status == 200
    assert response.body.to_s == "here's google"
  end
end

# in rspec
require "webmock"
require "httpx/adapters/webmock"
require "webmock/rspec"

describe "httpx calls" do
  before do
    stub_http_request(:get, "https://www.google.com").and_return(status: 200, body: "here's google")
  end
  it "mocks the request" do
    response = HTTPX.get("https://www.google.com")
    expect(response.status).to eq(200)
    expect(response.body.to_s).to eq("here's google")
  end
end

Caveats

Webmock won’t work for httpx sessions instantiated before loading it.

require "httpx"

client = HTTPX.plugin(:persistent)

require "httpx/adapters/webmock"
Webmock.enable!

# client var is not influenced by webmock
client.get(url) # real request

# this one will though!
client2 = HTTPX.plugin(:persistent)

To avoid surprises, load the webmock adapter before your application code.

Next: Considerations