Test helpers for stubbing Stripe HTTP requests.
Uses ownership-based stubs (via NimbleOwnership) so stubs are scoped to
the test process and work correctly with async: true tests.
Setup
In your test/test_helper.exs:
Stripe.Test.start()
ExUnit.start()Stubbing Requests
test "creates a charge" do
Stripe.Test.stub(fn %{method: :post, url: url} ->
assert url =~ "/v1/charges"
{200, [], ~s({"id": "ch_123", "object": "charge"})}
end)
client = Stripe.Test.client("sk_test_123")
{:ok, data} =
Stripe.Client.request(client, :post, "/v1/charges",
params: %{amount: 2000, currency: "usd"}
)
assert data["id"] == "ch_123"
endAsync Tests
Stripe.Test.client/2 captures the calling test process in the client's
transport, so spawned processes can use that client:
test "works from a spawned task" do
Stripe.Test.stub(fn _req -> {200, [], ~s({"ok": true})} end)
client = Stripe.Test.client("sk_test_123")
Task.async(fn ->
Stripe.Client.request(client, :get, "/v1/balance")
end)
|> Task.await()
endStub Function
The stub function receives a map with:
:method- HTTP method atom (:get,:post, etc.):url- Full URL string:headers- List of{name, value}tuples:body- Request body (string or nil)
And must return a {status, headers, body} tuple:
status- HTTP status code (integer)headers- Response headers as[{name, value}]body- Response body (string)
Summary
Functions
Allow child_pid to use the stub registered by owner_pid.
Create a Stripe client configured to use the current test process's stub.
Start the test stub server. Call this in test/test_helper.exs.
Register an HTTP stub for the current test process.
Return a transport function that uses the current test process's stub.
Functions
Allow child_pid to use the stub registered by owner_pid.
Use this when your test spawns processes that make Stripe API calls.
@spec client( String.t(), keyword() ) :: Stripe.Client.t()
Create a Stripe client configured to use the current test process's stub.
@spec start() :: {:ok, pid()}
Start the test stub server. Call this in test/test_helper.exs.
Register an HTTP stub for the current test process.
The stub function will be called instead of making real HTTP requests
for any Stripe.Client.request/4 call from this process.
Ownership is automatically cleaned up when the test exits.
@spec transport(pid()) :: Stripe.Client.transport()
Return a transport function that uses the current test process's stub.
Pass this as transport: Stripe.Test.transport() when constructing a client
manually.