Current section
Files
Jump to
Current section
Files
README.md
# Loopback
Run your tests against fake external services.
- *No changes to production code*: your app doesn't need behaviours, injected clients or configurable URLs to be testable, and neither do the libraries it uses, like SDKs for external services.
- *Better test coverage*: your code that builds requests, sets headers, authenticates, encodes data and handles errors runs in tests as in production.
- *Stateful fakes*: each fake is a process that keeps its state between requests. Tests set up data and check results through the fake's helpers.
- *Async tests*: each test gets its own fakes.
- *Familiar tools*: a fake is a `GenServer`, optionally with a routing DSL similar to `Plug.Router`.
- *No accidental real requests*: a request that no fake handles fails the test with a descriptive error.
- *No network*: your app's requests reach fakes in the same VM, without a server on localhost or open ports.
> New to fakes? See [why you'd want to use them](#why-fakes).
> This is a pre-1.0 package. The API may still change.
### Supported clients
| Client | Supported versions | Notes |
| --------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Finch | `~> 0.24` | Every request function, including streamed request bodies and the `[:finch, :request]` telemetry events, except for `async_request/3`. Mint, which Finch is built on, isn't intercepted when used directly. |
| hackney | `~> 1.21 or ~> 4.0 and >= 4.0.2` | Synchronous and asynchronous requests ([in one chunk](#limitations-of-interception)), including streamed request bodies, except for request bodies from a function. |
| `:httpc` | OTP 26+ | Synchronous and asynchronous requests, including request bodies from a function and the `:stream` option ([in one chunk](#limitations-of-interception)). |
| HTTPoison | `~> 2.2 or ~> 3.0` | Through hackney, including asynchronous responses ([in one chunk](#limitations-of-interception)). |
| Req | `~> 0.5` | Through Finch, Req's default adapter, including `into:` ([in one chunk](#limitations-of-interception)). |
| Tesla | `~> 1.22` | With `Tesla.Adapter.Finch`, `Tesla.Adapter.Gun`, `Tesla.Adapter.Hackney`, `Tesla.Adapter.Mint`, or the default `Tesla.Adapter.Httpc`. Streamed responses arrive [in one chunk](#limitations-of-interception), and `body_as: :chunks` isn't supported. |
Loopback currently supports HTTP, and the goal is to support low-level clients for any protocol. Adding another HTTP client requires writing an interceptor. See `Loopback.Interceptor` for details.
Requests made with other clients aren't intercepted and go to the real services. That includes requests your dependencies make, so check which client they use.
## Installation
Add Loopback to your dependencies in `mix.exs`:
```elixir
defp deps do
[
# First on the list, so that it starts before your other dependencies.
{:loopback, "~> 0.1", only: :test}
]
end
```
To also run your app against the fakes locally, see [Using fakes for local development](#using-fakes-for-local-development).
## Getting started
The following example shows a test for an application that sends emails using an HTTP API.
The app uses [Finch](https://finch.hexdocs.pm/Finch.html), so start by intercepting it in `config/test.exs`:
```elixir
config :loopback, intercept: [Loopback.Interceptors.Finch]
```
Your app calls the API as usual:
```elixir
defmodule MyApp do
def send_welcome_email(address) do
headers = [{"content-type", "application/json"}]
body = JSON.encode!(%{recipient: address, body: "Hi!"})
request = Finch.build(:post, "https://email.example.com/send", headers, body)
case Finch.request!(request, MyFinch) do
%{status: 201} -> :ok
_ -> :error
end
end
end
```
Write the fake in `test/support` using `Loopback.HTTPFake.Router` (in projects without Phoenix, add that directory to `elixirc_paths`):
```elixir
defmodule EmailServiceFake do
# A fake that handles requests containing "email.example.com" in the URL.
# Also adds helpers for its state, like get_state/0 and update_state/1.
use Loopback.HTTPFake.Router, match: "email.example.com"
alias Loopback.HTTPResponse
@impl true
def init(_opts) do
{:ok, %{emails: []}}
end
# A helper for tests.
def inbox_for(address) do
%{emails: emails} = get_state()
Enum.filter(emails, fn email -> email["recipient"] == address end)
end
# A route, like in Plug.Router. The request is available as `request`.
post "/send" do
email = JSON.decode!(request.body)
update_state(fn state -> %{state | emails: [email | state.emails]} end)
HTTPResponse.json(201, %{})
end
end
```
Start the fakes for each test, call your app and check the results with the fake's helpers:
```elixir
defmodule MyAppTest do
use ExUnit.Case, async: true
setup do
# Starts the fakes for this test only. They stop when the test ends.
Loopback.start_fakes!([EmailServiceFake])
end
test "sends a welcome email to the user" do
assert :ok = MyApp.send_welcome_email("nat@example.com")
assert [%{"body" => "Hi!"}] = EmailServiceFake.inbox_for("nat@example.com")
end
end
```
The [full example](https://github.com/stefanchrobot/loopback/blob/main/examples/email_service.exs) also simulates an outage of the email service and connection errors, like timeouts. Run it with `elixir examples/email_service.exs`.
## How Loopback works
Loopback replaces public functions of low-level clients, like Finch for HTTP. It does so when it starts, before your app and tests:
```mermaid
sequenceDiagram
participant Mix as mix test
participant Loopback
participant Client as Finch
participant App as MyApp
participant Test as Tests
Mix->>Loopback: start
Loopback->>Client: override with Interceptors.Finch
Mix->>App: start
Mix->>Test: run
```
Fakes are stateful processes, so async tests need their own fakes. Each test starts them during setup:
```mermaid
sequenceDiagram
participant TestA as Test A<br>PID<0.301.0>
participant TestB as Test B<br>PID<0.302.0>
participant Loopback
participant FakeA as EmailServiceFake<br>PID<0.401.0>
participant FakeB as EmailServiceFake<br>PID<0.402.0>
TestA->>Loopback: start_fakes!(fakes)
Loopback->>Loopback: register_owner(PID<0.301.0>)
Loopback->>FakeA: start_link(opts)
TestB->>Loopback: start_fakes!(fakes)
Loopback->>Loopback: register_owner(PID<0.302.0>)
Loopback->>FakeB: start_link(opts)
```
During a test, Loopback intercepts the requests your app makes, looks up the test's fakes and dispatches each request to the one that handles it:
```mermaid
sequenceDiagram
participant Test as Test A<br>PID<0.301.0>
participant App as MyApp
participant Client as Finch (overridden)
participant Loopback
participant Fake as EmailServiceFake<br>PID<0.401.0>
Test->>App: send_welcome_email(address)
App->>Client: Finch.request!()<br>POST https://email.example.com/send
Client->>Loopback: dispatch(request)
Loopback->>Loopback: lookup_fake(PID<0.301.0>)
Loopback->>Fake: handle(request)
Fake-->>Loopback: HTTP response
Loopback-->>Client: HTTP response
Client-->>App: Finch response
App-->>Test: :ok
Test->>Fake: inbox_for(address)
Fake-->>Test: list of emails
```
The fakes in the diagrams are per-test fakes, started by each test for the requests made by the code it calls. Loopback can also run global fakes, started before your app, for the requests made while your app boots. The two differ in how your tests and app interact with the fakes, as described below.
### Per-test fakes
A test's fakes are linked to it, so they stop when the test ends. A crashed fake isn't restarted, and it fails the test, since a crash in a fake is considered a bug. Requests made in `ExUnit.Callbacks.on_exit/2` callbacks don't reach the test's fakes, which have stopped by then.
The code under test often spawns different processes that make requests, like a `Task` or a `GenServer`. So to look up the fakes, Loopback goes through a list of processes, and uses the fakes of the first one that started fakes or is allowed to use them. The list is the calling process, followed by:
- Its callers: the processes it was started on behalf of, closest first, stored in its process dictionary under `:"$callers"`. `Task`, Phoenix channels and LiveView use this convention.
- Its parents: the process that spawned it, the one that spawned that one, and so on.
A fake's helpers, like `inbox_for/1`, find the fake's process the same way, with `Loopback.whereis!/1`.
Some processes aren't connected to the test through their callers or parents, like the ones your app started when it booted, children of your app's `DynamicSupervisor`, tasks started by your app's `GenServer`s, and `Oban` jobs in real queues. To reach the test's fakes, they need to be allowed with `Loopback.allow/2`, or the test has to start its fakes with `shared: true`, so that every process finds them. A shared test can't be async.
The test's fakes are tried first, in the order they're listed, then the [global ones](#global-fakes). When no fake matches, the `:unmatched` option of `Loopback.start_fakes!/2` decides whether to raise (the default) or to pass the request through to the real service.
### Global fakes
Your app starts before the test setup, so the requests it makes while it boots need global fakes. Configure them in `config/test.exs`:
```elixir
config :loopback,
intercept: [Loopback.Interceptors.Finch],
global_fakes: [FeatureFlagsFake]
```
`:intercept` lists the interceptors to install, and `:global_fakes` the fakes to start, as child specs. `:unmatched` decides what happens to a request from outside the tests that no global fake matches: `:raise` (the default), or `:passthrough`, which sends it to the real service.
Loopback starts as one of your dependencies. List `:loopback` first in `mix.exs`, so that it starts before the others, and intercepts the requests they may make while they start.
Every process reaches the global fakes, whatever its callers and parents, so there's nothing to allow. That includes the processes that a test forgot to allow: their requests go to the global fakes instead of the test's ones. When no fake matches and the process isn't connected to a test, the request raises.
Global fakes aren't linked to tests and they keep their state across tests, so a test should only read the state that it created. A global fake that crashes is restarted. If a test starts the same fake as a global one, the test's one comes first.
Global fakes start before your app, so their `init/1` can read config, but can't call your app's processes, or use the dependencies that start after Loopback, like a time zone database. A fake that needs them, for example to load data from your database, can do it on its first request or helper call, when your app is already running.
Global fakes are also how Loopback runs in local development, see [Using fakes for local development](#using-fakes-for-local-development).
### Limitations of interception
Interception applies to the whole node: the client is overridden for every process. The requests that your dependencies make with it are intercepted too, and like your app's, they need a fake, unless you switch them off in tests.
Responses aren't streamed. Streaming functions, like `Finch.stream/5` or Req's `into:`, get a fake's whole body as a single chunk, without trailers.
Interception requires debug info, since Loopback rebuilds the client's module from it. Mix includes it by default, but releases strip it, so to use fakes in a release, keep it with `strip_beams: [keep: ["Dbgi"]]` in the release's options in `mix.exs`.
## Why fakes?
_A fake_ is a working implementation of something your app depends on, like an email-sending API or cloud file storage, that you want to replace in tests. Fakes take shortcuts that make them unsuitable for production, like keeping all state in memory, ignoring multi-tenancy (supporting a single account) or implementing only the features your app uses.
Replacing a real external service in tests helps with:
- *Performance*: cut the runtime of your test suite by avoiding network latency and slow responses.
- *Reliability*: avoid transient issues that cause intermittent failures.
- *Isolation*: each test starts with a clean state, and concurrent tests don't affect each other.
- *Control*: trigger errors or rate limits in external services on demand.
- *Cost and access*: no need to set up external accounts or pay for usage.
All test doubles ([fakes, stubs and mocks](https://martinfowler.com/articles/mocksArentStubs.html#TheDifferenceBetweenMocksAndStubs)) can bring these improvements, but fakes have unique advantages:
- *Written once*: a fake describes the service's behaviour in one place, for every test. Tests only set up the data they need.
- *Consistent state*: what one request creates, the next one can read. Longer interactions work without preparing a response for each step and keeping those responses consistent with each other.
- *Refactoring-safe*: mocks verify which calls the app made, in what order and how many times. A fake has helpers for checking the service's state instead, like the emails it received, so the app can change how it calls the service without breaking the tests.
One cost of fakes is the extra code: keeping state and keeping it consistent takes more effort than writing canned responses. It's written once, though, and it mostly follows the service's API documentation, which makes it a good task for a coding agent.
The other cost is the risk of fakes not being faithful to the real service. A fake that accepts requests the service rejects keeps your tests green while production breaks.
A real dependency is still the better choice when it's fast, reliable and supports isolated tests. [Testing against a real database with Ecto](https://ecto.hexdocs.pm/testing-with-ecto.html) is a great example. Prefer real implementations, then fakes, over stubs and mocks.
## Compared to other approaches
Approaches differ in where the replacement is plugged in. That decides how much of your app runs in tests, and what your production code has to do to make room for it:
| Approach | Examples | Runs your client code | Production code |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| Explicit interfaces for API clients | [Mox](https://mox.hexdocs.pm/Mox.html) | No | Puts the client behind a behaviour and looks up which implementation to use. |
| Configuring the client library | [Req.Test](https://req.hexdocs.pm/Req.Test.html), [Tesla's mock adapter](https://tesla.hexdocs.pm/1-testing.html) | Yes | May have to pass the test options along. |
| Running a local server | [Bypass](https://bypass.hexdocs.pm/Bypass.html) | Yes, and the network stack | Needs a configurable base URL. In async tests, each test's server has its own URL, so it can't come from global config. |
| Replacing modules at runtime | [Meck](https://meck.hexdocs.pm/readme.html), [Mock](https://mock.hexdocs.pm/Mock.html), [Patch](https://patch.hexdocs.pm/readme.html), [Mimic](https://mimic.hexdocs.pm/readme.html) | Depends on the module you replace | Unchanged. |
| Intercepting low-level clients | Loopback | Yes | Unchanged. |
What kind of test double you use is a separate choice: you could put a fake behind a Mox behaviour, or serve canned responses from Bypass. Most of these tools are built around stubs and mocks.
Loopback replaces functions at runtime too, but only in low-level clients, like Finch. Your app builds and makes requests as in production, and Loopback hands them to a fake instead of sending them over the network. The fakes don't depend on your code, so they stay the same when you refactor the app. They change only when your app starts using more of the service's API, or when the service changes it.
If your tests also stay away from your app's internals, a wide range of refactorings won't touch the test code at all. That's the testing approach described in the next section.
## Automated manual testing
Your app's users care about what it does, not how. The most valuable test would check that behaviour in production, but that's not feasible for a suite that runs after every change. The closer a test gets to production, the better.
[Acceptance tests](https://en.wikipedia.org/wiki/Acceptance_testing) check that your app meets its requirements by going through the steps a user would take. They're usually run in a staging environment that's meant to be a copy of production. Often, they're manual, and slow as a result. If automated, they tend to fail due to an unreliable environment.
At the other end, [unit tests](https://martinfowler.com/bliki/UnitTest.html) are fast and reliable, but they often focus on units of code, like modules and functions, which rarely map to requirements. How big a unit is, though, is up to you, and it can be a unit of behaviour that spans your whole app. As long as everything runs in one operating system process, the tests keep their speed and reliability.
_Automated manual testing_ combines the two: tests that check requirements, like acceptance tests, and run like unit tests. You take the steps a manual tester would follow through your app's entrypoints, like its UI, API or event bus, and turn them into code. You run the whole app in the same operating system process as the tests, and replace the services your team doesn't own with fakes. You assert on what your users would see, and query the database or read the logs only as a last resort. These tests are the core of your test suite. With this approach, you get the confidence of testing close to production, at nearly the speed of traditional unit tests.
With Loopback, your app runs unchanged: Loopback intercepts its requests at the low-level client, so everything above it runs as in production, and the requests reach stateful fakes.
### Example: inviting a team member
Consider a web app where users can invite their team members to their account. The app has a REST API for sending invites, and each invite sends an email with an activation link.
To test this flow, a manual tester would:
1. Sign up for an account in the app.
2. Create an API key for the account.
3. Send an HTTP request to invite a team member.
4. Find the invitation email in the team member's inbox.
5. Open the link and check that the page asks the team member to activate their account.
The tester needs to know the app's entrypoints: its web pages, the API endpoint, the format of requests and responses, the authentication scheme and how to get credentials. They can ignore the app's language, framework and database, and how its code is organized.
The test follows the same steps:
```elixir
test "users can invite their team members" do
account = App.sign_up()
api_key = App.create_api_key(account)
assert %{status: 201} =
HTTP.post("/api/user_invites", %{email: "nat@example.com"}, api_key: api_key)
assert [%{"body" => body}] = EmailInbox.open("nat@example.com")
link = App.extract_activation_link(body)
page = Browser.open(link)
assert page =~ "Activate your account"
assert page =~ "nat@example.com"
end
```
### Helpers
The test reads like the steps because helpers hide the details:
- `App` handles common flows, like signing up, creating an API key or extracting the activation link from an email.
- `HTTP` makes requests to your app's API. It handles JSON and authentication, and can be built on [`Phoenix.ConnTest`](https://phoenix.hexdocs.pm/Phoenix.ConnTest.html).
- `EmailInbox` opens an address's inbox. It's built on a fake of your email service.
- `Browser` opens pages, and can be built on `HTTP` or [PhoenixTest](https://hex.pm/packages/phoenix_test).
You write the helpers once and reuse them across tests. They're also where your app's internals are encapsulated, like how an account is created or how emails are delivered. When the internals change, a helper changes. The test changes only when requirements change.
### How this fits with Elixir
Your app and its tests run in the same VM, and the tests can still run concurrently, each with its own data and fakes. [Ecto's SQL sandbox](https://ecto-sql.hexdocs.pm/Ecto.Adapters.SQL.Sandbox.html) gives each test its own transaction. The database runs in its own operating system process, but tests stay fast, concurrent and isolated while exercising your app's persistence layer. Fakes are processes, so starting them for each test is cheap. Tasks and LiveViews reach the test's fakes through `$callers`.
Helpers can drive your app without a real server or browser, using [`Phoenix.ConnTest`](https://phoenix.hexdocs.pm/Phoenix.ConnTest.html) and [`Phoenix.LiveViewTest`](https://phoenix-live-view.hexdocs.pm/Phoenix.LiveViewTest.html). Background jobs can run in the test, too. With [`Oban`](https://oban.hexdocs.pm/Oban.html), a common choice for them, a helper like `EmailInbox.open/1` runs the queued jobs in the test's process before opening the inbox, and fails the test if a job fails. The jobs' requests reach the test's fakes.
### Limitations
Some things are hard to reach through your entrypoints:
- *Failures inside your app*, like losing the connection to the database.
- *Concurrency*, like two requests updating the same record at once.
- *Time*, like an activation link that expires after a day. Controlling the clock needs a hook in your app.
Test these with narrower tests. Logic with many cases, like validation rules, is also often a better fit for short unit tests or doctests, although you can run such cases through the whole stack too, with tests generated in a loop.
Tests that go through your entrypoints are harder to debug: a failing test shows what broke, but not where. The logs help, and ExUnit's [`:capture_log`](https://ex-unit.hexdocs.pm/ExUnit.html#configure/1-options) option prints them only for failing tests.
Setting up data through your entrypoints is slower than inserting rows into the database, but that's the price of realistic scenarios.
Sometimes a scenario can't be set up through your entrypoints at all. For example, your app may still have to handle data it can no longer create, like records from a feature you've removed. Because the tests run in your app's process and language, they can insert those records directly. Use such escape hatches sparingly, since they tie a test to your app's internals.
### Related approaches and further reading
- [In-process component tests](https://martinfowler.com/articles/microservice-testing/) (Toby Clemson): the closest one. The whole app runs in the same operating system process as the tests, driven through its API, with test doubles for the services it calls. The app usually starts in a test mode, though, which swaps its dependencies for stubs and its datastores for in-memory ones.
- [Testing honeycomb](https://engineering.atspotify.com/2018/01/11/testing-of-microservices) (Spotify): most tests go through a service's API, with a real database and no other services. It describes a test portfolio, not how to write each test.
- [Hermetic servers](https://testing.googleblog.com/2012/10/hermetic-servers.html) (Google): the whole system on one machine without a network, with test doubles injected through dependency injection.
- [How to Write Acceptance Tests](https://www.youtube.com/watch?v=JDD5EEJgpHU) (Dave Farley): acceptance tests in four layers, with test cases, a domain-specific language, protocol drivers and the system under test. The helpers in the example above play the role of the language and the drivers, but Farley's tests run against an app deployed to a production-like environment.
- [Testing Without Mocks](https://www.jamesshore.com/v2/projects/nullables/testing-without-mocks) (James Shore): sociable, state-based tests too, but with "nullable" infrastructure, an off switch built into production code. Loopback leaves production code unchanged.
- [TDD, Where Did It All Go Wrong](https://www.infoq.com/presentations/tdd-original/) (Ian Cooper): tests should check behaviour through a public API, not the implementation, so the unit of a test is a unit of behaviour. Testing through your entrypoints applies the idea to the whole app.
- [How to Stub External Services in Tests](https://thoughtbot.com/blog/how-to-stub-external-services-in-tests) (thoughtbot): intercepting requests in Ruby. WebMock sends them to a fake written in Sinatra, as Loopback does with `Loopback.HTTPFake.Router`.
- [Mock Service Worker](https://mswjs.io/): intercepting requests in JavaScript, in the browser and in Node.js.
## Using fakes for local development
The fakes you write for tests can also be used when you run your app locally, with no accounts, API keys or network connection to worry about. You can call the fakes' helpers from IEx, the same ones your tests use, or build a dev-only page on top of them to view and edit the fakes' state.
Start by adding Loopback to your dependencies in development too. Your fakes also need to compile in development, so add their directory to `elixirc_paths`:
```elixir
defp deps do
[
# First on the list, so that it starts before your other dependencies.
{:loopback, "~> 0.1", only: [:dev, :test]}
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(:dev), do: ["lib", "test/support/fakes"]
defp elixirc_paths(_), do: ["lib"]
```
Then configure Loopback in `config/dev.exs`, the same way as in `config/test.exs`. In development, the fakes are [global fakes](#global-fakes):
```elixir
config :loopback,
intercept: [Loopback.Interceptors.Finch],
global_fakes: [EmailServiceFake],
# Requests that no fake matches go to the real services.
unmatched: :passthrough
```
To use the real service instead of a fake, leave the fake out of `:global_fakes`, or return `:ignore` from its `init/1`.
Loopback is a dependency only in development and tests, so your release includes neither Loopback nor your fakes.
## License
Copyright (c) 2026 Stefan Chrobot. Released under the MIT License. See the `LICENSE` file.