Testing
- Introduction
- Writing tests
- Configuring your tests
- Making requests
- Available assertions
- Testing JSON APIs
- Testing views
- Testing head metadata
- Testing errors
- Testing the database
- Fakes
- Swapping services
- Time travel
- Testing without requests
- Testing console commands
- Troubleshooting tests
Introduction
dust-framework is built with testing in mind. You can send HTTP requests directly through your application's full middleware, routing, and handler stack without binding a network port, then assert on the resulting responses in a few lines of code:
use dust::testing::prelude::*;#[dust::test]async fn the_application_returns_a_successful_response(app: Application) { app.get("/").await.assert_ok();}In this test, app.get("/") dispatches a GET request through your full middleware, routing, and error-handling pipeline, and assert_ok() verifies a 200 status code. Writing feature tests like this exercises your routes, middleware, and handlers together as real browser requests hit them.
dust::testing::prelude imports everything from the prelude along with the test client traits on Application and the json! macro for building JSON payloads and assertions.
Writing tests
Place integration tests in the tests/ directory and annotate each test function with #[dust::test]. A test's parameters declare what it needs, so a test with no parameters runs as a lightweight unit test without booting an application:
use dust::testing::prelude::*;#[dust::test]fn titles_become_slugs() { assert_eq!("dust-framework Is Here!".slug(), "dust-is-here");}For general value assertions, use Rust's built-in assert!, assert_eq!, and assert_ne! macros:
assert!(user.is_admin);assert!(!user.is_suspended);assert_eq!(invoice.total, 12_000);assert_ne!(user.email, "other@example.com");An Application argument gives the test a fresh application of its own, which Configuring your tests describes. The whole test runs inside the application, so you may call functions such as crypt::encrypt_string or dust::config() directly. Name the argument _app when you only need those functions:
use dust::crypt;use dust::testing::prelude::*;#[dust::test]fn secrets_can_be_decrypted(_app: Application) -> dust::Result<()> { let payload = crypt::encrypt_string("secret")?; assert_eq!(crypt::decrypt_string(&payload)?, "secret"); Ok(())}A test may be async and return a Result so you can use ?. Each test runs with isolated services, clock, and memoized values so concurrent tests never interfere.
Running tests
Run your tests with Cargo. To run only some of them, pass part of their names:
cargo testcargo test invitationsCargo runs your tests in parallel, and cargo nextest run works too. Each test runs with an isolated application and, when you enable refresh_database, an isolated database, so tests never wait on each other.
What a test boots
#[dust::test] decides how much of the application a test starts, based on its signature:
| Test signature | What runs | Use it for |
|---|---|---|
fn name() |
Nothing; a plain unit test. | Pure functions, string helpers, value objects. |
fn name(_app: Application) |
A booted application, with its configuration and services. | Code that reads dust::config(), encrypts, or resolves a service. |
async fn name(app: Application) |
A booted application with an async test body. | HTTP requests, database work, jobs, listeners. |
async fn name() -> dust::Result<()> |
Nothing, but ? works. |
Async helpers that don't need the application. |
A test that takes Application gets a fresh one, never a shared global. The test body runs inside that application's context, so dust::config() and dust::resolve work without a handler. The application boots once per test; the HTTP client reuses it for every request in the body.
Tests are isolated in more than the database: the clock, memoized once values, container services, session, and cache all belong to the test's application. Two tests that travel to different dates, swap different services, or share a cache key never see each other's state, even when Cargo runs them in parallel.
Configuring your tests
Application tests call app::testing::create. In an application that doesn't have src/testing.rs yet, create it so the test attribute has a factory to call:
// src/testing.rsuse dust::Application;use dust::foundation::ApplicationBuilder;pub fn configure() -> ApplicationBuilder { crate::configure().for_testing(env!("CARGO_MANIFEST_DIR"))}pub fn create() -> Application { configure().create()}It builds your application with for_testing, which loads your .env file (with variables set in your shell taking precedence), sets APP_ENV to testing and APP_BASE_PATH to the crate's directory, and fills in a fresh APP_KEY when none is set. It also applies these fast defaults unless .env or your shell sets the variable:
| Variable | Test value | Why |
|---|---|---|
APP_DEBUG |
true |
A failure page names the template or line. |
BCRYPT_ROUNDS |
4 |
Hashing a password in every test stays cheap. |
BROADCAST_CONNECTION |
discard |
A broadcast doesn't need a running relay. |
CACHE_STORE |
memory |
Each test has its own cache, with no shared server. |
FEATURE_STORE |
memory |
A flag's result belongs to the test. |
MAIL_MAILER |
log |
Mail is written to the log, not sent. |
OTEL_SDK_DISABLED |
true |
A test doesn't export traces. |
QUEUE_CONNECTION |
sync |
A dispatched job runs during the test. |
SESSION_DRIVER |
memory |
Sessions stay inside the test application. |
SMS_SENDER |
log |
SMS is written to the log, not sent. |
WORKFLOW_STORE |
memory |
A workflow run belongs to the test. |
These are fallbacks, not overrides: a value in .env or the shell wins. Any variable in .env that isn't a fallback, such as DATABASE_URL or your application's own API keys, takes effect as usual. If a variable in .env is missing or empty, for_testing fills in the defaults above so tests still run.
To change a variable for every test, add or edit an entry in with_envs inside src/testing.rs. To let a .env value take effect instead of a fallback, such as testing against a Redis cache configured in .env, set the variable in .env; the fallback only applies when it is unset.
In the testing environment, every job goes to the default queue connection, even one that names its own connection, so queued work runs during the test.
You may also create a .env.testing file in your project root. When .env.testing exists, for_testing reads it instead of .env, and the overrides in src/testing.rs still apply on top of it.
To override a variable for only some tests, write a function that starts from app::testing::configure(), chains with_env or with_envs, and returns an Application, then name it in the test's attribute:
use dust::testing::prelude::*;fn app_in_euros() -> Application { app::testing::configure().with_env("BILLING_CURRENCY", "eur").create()}#[dust::test(app = app_in_euros)]async fn prices_are_shown_in_euros(app: Application) { app.get("/pricing").await.assert_see("€");}A test that names a factory still runs inside its application when it takes no argument, so it may leave the argument out when it only calls functions such as dust::config().
Making requests
Send HTTP requests in a test by calling get, post, put, patch, or delete on app and awaiting the request, which returns a TestResponse for chaining assertions:
use dust::testing::prelude::*;#[dust::test]async fn posts_are_listed(app: Application) { app.get("/posts").await.assert_ok().assert_see("Posts");}Requests target the host configured in APP_URL from 127.0.0.1, and the test client automatically marks them as same-origin requests so CSRF protection allows them through.
Customizing request headers
Use header to attach custom headers to a test request:
app.get("/users") .header("accept", "application/json") .header("accept-language", "fr") .await .assert_ok();To authenticate an API request with a bearer token, call token, which sets the Authorization header:
app.get("/api/me").token("my-api-token").await.assert_ok();To simulate a request arriving from a specific IP address, such as when testing trusted proxies or rate limits, call with_ip:
app.post("/login").with_ip([203, 0, 113, 7]).await.assert_redirect();Sending input
Use form to send an application/x-www-form-urlencoded body, the format an HTML form posts, and json to send application/json. Both take a list or a JSON value, and both are available on every request method:
use dust::testing::prelude::*;#[dust::test]async fn users_can_sign_up(app: Application) { app.post("/sign-up") .form([ ("name", "Taylor"), ("email", "taylor@example.com"), ("password", "secret123"), ("password_confirmation", "secret123"), ]) .await .assert_redirect_to("/dashboard"); app.post("/api/users") .json(json!({ "name": "Abigail", "email": "abigail@example.com" })) .await .assert_created();}To send a raw request body verbatim, such as a signed webhook payload, use body together with header for the content type:
app.post("/webhooks/stripe") .header("content-type", "application/json") .body(r#"{"type": "invoice.paid"}"#) .await .assert_ok();Uploading files
To test file uploads, pass an Attachment to attach, which encodes the request as a multipart form alongside any form fields. Attachment::from_path reads a fixture file relative to your application's base path:
use dust::http::client::Attachment;app.post("/avatar") .attach("avatar", Attachment::from_path("tests/fixtures/taylor.png")) .form([("name", "Taylor")]) .await .assert_ok();For files created inline during a test, use Attachment::from_data(bytes, "taylor.png").
To test file size limits or image uploads without checking fixture files into your repository, use Attachment::fake(name, kilobytes) or Attachment::fake_image(name, width, height) (which generates a valid PNG):
app.post("/avatar") .attach("avatar", Attachment::fake_image("taylor.png", 640, 480)) .await .assert_ok();app.post("/documents") .attach("document", Attachment::fake("report.pdf", 6_000)) .await .assert_invalid(&["document"]);Because Attachment::fake fills the file with zero bytes, validation rules that inspect file contents (such as image or mimes) will reject it.
Cookies and sessions
Each test request starts with an empty cookie jar. To carry cookies (including the session cookie) from one response into a subsequent request, pass the first response to with_cookies_from:
let first = app.post("/settings/theme").form([("theme", "dark")]).await;app.get("/settings") .with_cookies_from(&first) .await .assert_see("Dark theme");Use with_session to seed session data before a request runs, and assert_session_has or assert_session_missing to verify what the handler stored or flashed:
app.post("/checkout") .with_session(json!({ "coupon": "WELCOME10" })) .await .assert_redirect_to("/orders") .assert_session_has("status", "Order placed!") .assert_session_missing("coupon");Session keys support dot notation such as settings.theme. Use assert_session_present to check only that a key exists, or assert_session_where to inspect a deserialized session value with a closure:
app.post("/cart") .form([("product", "7")]) .await .assert_session_present("cart") .assert_session_where("cart", |cart: Vec<u64>| cart.contains(&7));Session helpers apply only to routes running the session middleware (such as routes in the web group).
To send a cookie with a request, pass its plain-text value to cookie(name, value). dust-framework handles cookie encryption automatically so your handler receives the value whether or not EncryptCookies runs on that route. On the response, assert decrypted cookie values with assert_cookie, removed cookies with assert_cookie_expired, or presence with assert_cookie_present and assert_cookie_missing:
app.get("/").cookie("theme", "dark").await.assert_see("dark");app.post("/theme") .form([("theme", "dark")]) .await .assert_cookie("theme", "dark");app.post("/tour/dismiss").await.assert_cookie_expired("tour");Acting as a user
To send a request as a logged-in user, use acting_as:
use dust::model::create;use dust::testing::prelude::*;#[dust::test]async fn users_see_their_dashboard(app: Application) -> dust::Result<()> { let user = create!(User { name: "Taylor", email: "taylor@example.com", password: "password", }) .await?; app.get("/dashboard").acting_as(&user).await.assert_ok(); Ok(())}To verify authentication state after a login, registration, or logout request, use assert_authenticated, assert_authenticated_as(&user), or assert_guest:
app.post("/login") .form([("email", "taylor@example.com"), ("password", "password")]) .await .assert_redirect_to("/dashboard") .assert_authenticated_as(&user);app.post("/login") .form([("email", "taylor@example.com"), ("password", "wrong")]) .await .assert_guest();Following redirects
To test the page that a form redirects to, call follow_redirects:
app.post("/posts") .form([("title", "Hello")]) .follow_redirects() .await .assert_ok() .assert_see("Post created!");The test client follows each redirect with a GET and carries the cookies along, so the session and its flashed data reach the final page. It stops at a redirect to another site, such as a payment provider, and returns that redirect for you to check with assert_redirect_to.
Redirecting back
A form that fails validation redirects back to the previous page carrying the validation errors and flashed input. Tell the test client which page the request originated from using from, then verify the redirect with assert_redirect_back_with_errors:
use dust::testing::prelude::*;#[dust::test]async fn sign_ups_need_a_valid_email(app: Application) { app.post("/sign-up") .from("/sign-up") .form([("name", "Taylor"), ("email", "taylor"), ("password", "secret123")]) .await .assert_redirect_back_with_errors(&["email"]) .assert_session_has_input("email", "taylor") .assert_session_missing_input("password");}from sets the request's Referer header. assert_redirect_back checks only the redirect, and assert_redirect_back_without_errors checks that the session has no validation errors too. assert_session_has_input checks the old input that the next page reads with request.old, and password fields are never flashed.
Available assertions
Every request returns a TestResponse, and every assertion borrows it, so you chain as many as a test needs. The sections below group them by what they check. If an assertion fails, its message prints the response's status, headers, and body, so start there before adding a debug print.
Status assertions
Use assert_status with a status code number or StatusCode, or call one of the named helpers for common HTTP statuses:
app.get("/posts").await.assert_ok();app.post("/api/posts").json(json!({ "title": "Hello" })).await.assert_created();app.delete("/api/posts/1").await.assert_no_content();app.get("/missing").await.assert_not_found();app.get("/custom").await.assert_status(418);| Method | Asserts |
|---|---|
assert_status(code) |
The exact status code, as a number or StatusCode |
assert_ok(), assert_created(), assert_accepted(), assert_no_content() |
A 200, 201, 202, or 204; assert_no_content also checks the body is empty. |
assert_successful(), assert_client_error(), assert_server_error() |
Any 2xx, 4xx, or 5xx status |
assert_bad_request(), assert_unauthorized(), assert_forbidden(), assert_not_found() |
A 400, 401, 403, or 404 |
assert_unprocessable(), assert_too_many_requests(), assert_internal_server_error() |
A 422, 429, or 500 |
Redirect assertions
Verify redirect responses and their target URLs or routes:
app.post("/posts") .form([("title", "Hello")]) .await .assert_redirect_to(route!(posts::index)?);app.post("/orders") .form([("plan", "pro")]) .await .assert_redirect_to(route!(orders::show, &order)?);app.post("/invitations") .form([("email", "abigail@example.com")]) .await .assert_redirect_to_signed_route(invitations::accept, &invitation);| Method | Asserts |
|---|---|
assert_redirect(), assert_found(), assert_moved_permanently() |
Any redirect, a 302, or a 301 |
assert_redirect_to(path), assert_redirect_contains(text) |
A redirect to the path or URL, or to a URL containing the text |
assert_redirect_to_route(handler, params) |
A redirect to the route of a handler |
assert_redirect_to_signed_route(handler, params) |
A redirect to a valid signed URL for the route |
assert_redirect_back(), assert_redirect_back_with_errors(&[..]), assert_redirect_back_without_errors() |
A redirect back to the page the request came from |
Header and download assertions
Check response headers or verify that a response initiates a file download:
app.get("/api/posts") .await .assert_header("x-request-id", "req_123") .assert_header_contains("cache-control", "no-store") .assert_header_present("etag") .assert_header_missing("x-powered-by");app.get("/invoices/1/download") .await .assert_ok() .assert_download("invoice-1.pdf");| Method | Asserts |
|---|---|
assert_header(name, value), assert_header_contains(name, text) |
A header's exact value, or a substring of it |
assert_header_present(name), assert_header_missing(name) |
That a header is present, or absent |
assert_download(name) |
That the response downloads a file with the given filename |
Content assertions
Assert on the text or raw HTML rendered in a response body:
app.get("/posts") .await .assert_ok() .assert_see("Taylor's Post") .assert_dont_see("Draft Post") .assert_see_in_order(&["First Post", "Second Post"]) .assert_see_html("<h1>Posts</h1>");| Method | Asserts |
|---|---|
assert_see(text), assert_dont_see(text) |
That the body contains the text (or doesn't), matching both plain and HTML-escaped text |
assert_see_in_order(&[..]) |
That the body contains each string in sequence |
assert_see_html(markup), assert_dont_see_html(markup) |
That the body contains the raw HTML markup verbatim (or doesn't) |
Validation assertions
Check which fields failed or passed validation. These assertions work for both JSON 422 responses and session-flashed web errors:
app.post("/sign-up") .form([("name", "Taylor"), ("email", "not-an-email")]) .await .assert_invalid(&["email", "password"]) .assert_valid(&["name"]) .assert_invalid_messages(&[("email", "valid email")]);app.post("/settings/password") .form([("password", "short")]) .await .assert_invalid_in("password", &["password"]);| Method | Asserts |
|---|---|
assert_invalid(&[..]), assert_valid(&[..]) |
That the listed fields have validation errors, or have none |
assert_invalid_messages(&[(field, text)]) |
That each field has an error message containing the given text |
assert_invalid_in(form, &[..]) |
That the listed fields have errors in a named form |
Inspecting responses directly
For custom assertions beyond these helpers, inspect the response directly with status(), header(name), cookie(name), text(), and json(). Because each assertion borrows the response, bind it to a variable if you also want to reuse its cookies or print its body while debugging:
let response = app.get("/posts").await;response.assert_ok().assert_see("Posts");println!("{}", response.text());Cargo suppresses output from passing tests unless you pass -- --nocapture to cargo test.
Testing JSON APIs
assert_json performs a partial match starting from the root of the response JSON. Mirror the structure down to the fields you care about, and dust-framework ignores any extra keys on objects (such as id, email, or meta) as well as extra trailing items in arrays. Array elements are compared in order starting from index 0.
For example, if /api/users returns:
{ "data": [ { "id": 1, "name": "Taylor", "email": "taylor@example.com" }, { "id": 2, "name": "Abigail", "email": "abigail@example.com" } ], "meta": { "total": 2 }}You only need to specify the keys you want to verify:
use dust::testing::prelude::*;#[dust::test]async fn users_are_listed(app: Application) { app.get("/api/users") .await .assert_ok() .assert_json(json!({ "data": [ { "name": "Taylor" }, { "name": "Abigail" }, ], }));}When the assertion fails, the failure message points directly to the first mismatched path, such as data.1.name.
To assert a single value using dot notation, call assert_json_path; to check an array's length, use assert_json_count or assert_json_count_at:
app.get("/api/users") .await .assert_json_path("data.0.name", "Taylor") .assert_json_count_at("data", 2);To inspect a deserialized value with custom logic, pass a typed closure to assert_json_path_where, or verify that a key is absent with assert_json_missing_path:
app.get("/api/users") .await .assert_json_path_where("meta.total", |total: u64| total >= 2) .assert_json_missing_path("data.0.password");When you want to match the entire JSON payload with no extra keys or elements, use assert_exact_json, or assert_similar_json to ignore array ordering.
Whereas assert_json matches from the root of the response, assert_json_fragment verifies that a JSON object appears anywhere in the payload (such as one item inside an array), and assert_json_missing verifies that it does not appear anywhere:
app.get("/api/users") .await .assert_json_fragment(json!({ "name": "Taylor", "role": "admin" })) .assert_json_missing(json!({ "name": "Jess" }));To verify the keys and nesting of a JSON payload without pinning down exact values, use assert_json_structure. Arrays list required keys, objects map keys to nested structures, and "*" validates every item in an array:
app.get("/api/users") .await .assert_json_structure(json!({ "data": { "*": ["id", "name", { "team": ["id", "name"] }] }, "meta": ["total"], }));Use assert_exact_json_structure if unexpected extra keys should also fail the test.
Fluent JSON assertions
API responses can accidentally start exposing unintended fields, such as a sensitive attribute added to a model. assert_json_matches passes a fluent assertion builder to your closure and fails if any key in the response is left unchecked unless you explicitly opt out with etc():
use dust::testing::prelude::*;#[dust::test]async fn users_are_shown_without_their_password(app: Application) { app.get("/api/users/1").await.assert_json_matches(|json| { json.equals("id", 1) .equals("name", "Taylor") .missing("password") .scope("team", |team| team.has("id").etc()) });}Use scope to zoom into a nested object or array (paths inside the closure are relative to that path), first to inspect an array's first element, each to assert on every element, and etc() to allow remaining unchecked keys:
app.get("/api/users").await.assert_json_matches(|json| { json.has_count("data", 2) .first("data", |user| user.equals("name", "Taylor").etc()) .each("data", |user| user.satisfies("id", |id: u64| id > 0).missing("password").etc()) .etc()});| Method | Asserts |
|---|---|
has(path), has_any(&[..]), missing(path) |
That a path has a value, that one of the paths does, or that it has none |
equals(path, value) |
The value at a path |
satisfies(path, check) |
That the value at a path passes your check, read as the closure's argument type |
contains(path, item) |
That a list item or object value equals item in full |
has_count(path, n), has_count_in(path, range) |
How many items a list or object has |
scope(path, ..), first(path, ..), each(path, ..) |
The value at a path, a list's first item, or each item, in a closure |
etc() |
Nothing: it allows the keys the closure doesn't assert on |
Testing views
A response that rendered a view records the view's name and the template data passed to it:
use dust::model::create;use dust::testing::prelude::*;#[dust::test]async fn the_user_list_shows_each_user(app: Application) -> dust::Result<()> { create!(User { name: "Taylor", email: "taylor@example.com", password: "password" }).await?; app.get("/users") .await .assert_view_is("users.index") .assert_view_has("users.0.name", "Taylor"); Ok(())}Testing head metadata
A response that rendered a view also records its <head> metadata, so you can assert the title, description, canonical URL, and meta tags without parsing HTML. assert_head() returns a builder; chain the fields you care about and it fails on a missing or different value:
app.get("/posts/1") .await .assert_head() .title("Hello World · dust-framework") .meta("og:title", "Hello World · dust-framework") .missing("robots");For the full list of <head> assertions, check out testing the head in the head metadata guide.
Testing errors
A response rendered for an error retains the original error, so you can assert against the error type directly instead of matching HTML output. For example, suppose your checkout handler fails with a custom PaymentFailed error. assert_error checks the error type, and assert_error_where inspects its fields as well:
app.post("/checkout").await.assert_payment_required().assert_error::<PaymentFailed>();app.post("/checkout") .await .assert_error_where(|error: &PaymentFailed| error.reason == "insufficient funds");assert_reported::<E>() verifies that an error of type E was reported (either because it failed the request or because it was passed to dust::report). Use assert_not_reported::<E>() to verify that no error of type E was reported, and assert_nothing_reported() to assert that no errors were reported at all.
Testing the database
Tests that create users or place orders need a migrated database isolated from other tests. dust-framework gives each test its own database copy and rolls back all writes automatically when the test finishes.
Refreshing the database
To give each test a clean database built from your migrations, call refresh_database in src/testing.rs. It reads DATABASE_URL from your .env or .env.testing file, or you may point it at a separate test database in src/testing.rs:
use dust::foundation::ApplicationBuilder;pub fn configure() -> ApplicationBuilder { crate::configure() .for_testing(env!("CARGO_MANIFEST_DIR")) .with_env("DATABASE_URL", "postgres://postgres@127.0.0.1/io_test") .refresh_database()}Each test borrows a numbered copy of that database, such as io_test_1, that no other running test uses, so tests run in parallel. dust-framework creates the copies on PostgreSQL and MySQL, so the database user needs permission to create databases.
The copies stay between test runs, so your tests don't wait for the migrations every time. When you change your application's code, including a migration or a schema file, dust-framework rebuilds the copies. Changing only your tests doesn't. To rebuild the copies anyway, such as after editing a file that a migration reads, touch a source file before you run your tests:
touch src/app.rs && cargo testEach test runs in a transaction that's never committed, so its changes disappear when the test ends. Keep these differences in mind:
- Auto-increment IDs keep counting from one test to the next, because a rollback doesn't reset them. Assert the IDs that your application returns, not fixed ones such as
1. - Create tables in migrations, not in tests. On MySQL, a statement such as
CREATE TABLEcommits the transaction. - Rows that a test writes aren't visible to other processes, such as a queue worker you started yourself.
If your application has hundreds of migrations, rebuilding the copies can take a while. To build them faster, squash your migrations into a schema file. dust-framework loads the file into each copy, then runs only the migrations you've added since.
To give a test the rows it needs, create them with create! (as in Acting as a user) or with model factories.
Seeding the database
If a test only needs one or two records, prefer model factories over a seeder so each test clearly shows the data it relies on:
let user = User::factory().create().await?;let posts = Post::factory() .for_(Post::user, &user) .count(3) .create() .await?;When a test needs a larger set of fixture data, call seed with one of your seeders. It runs in the test's transaction, so its rows disappear when the test ends:
use app::seeders;use dust::testing::prelude::*;#[dust::test]async fn the_archive_lists_every_post(app: Application) -> dust::Result<()> { app.seed(seeders::posts).await; app.get("/archive").await.assert_ok().assert_see("Archive"); Ok(())}When most of your tests need the same rows, such as your roles, seed each test database once instead. Call seed_once in src/testing.rs:
pub fn configure() -> ApplicationBuilder { crate::configure() .for_testing(env!("CARGO_MANIFEST_DIR")) .refresh_database() .seed_once(crate::seeders::roles)}The seeder runs once for each copy of the test database, right after the migrations. Each test rolls back only its own changes, so every test starts with the seeded rows, including tests that count or list rows. Like the migrations, the seeder runs again when you change your application's code.
A test may still call seed for the rows it adds on top. Seeders that already ran for the copy don't run again, so a test that seeds users, which calls roles, doesn't create the roles twice.
To run a seeder before every test of a test application, without keeping its rows between tests, call seed on the builder:
fn app_with_posts() -> Application { app::testing::configure().seed(app::seeders::posts).create()}#[dust::test(app = app_with_posts)]async fn the_archive_paginates(app: Application) { app.get("/archive?page=2").await.assert_ok();}Both seed and seed_once require refresh_database to be enabled on your test application. Because refresh_database runs each test against an isolated database copy and rolls back changes automatically, requiring it prevents a test seeder from accidentally writing fixture data into a shared or local development database.
Database assertions
To check what your application wrote, use assert_database_has and the other database assertions. Each one reads the table when you await it:
use dust::testing::prelude::*;#[dust::test]async fn cancelling_an_import_fails_it(app: Application) { app.post("/imports/7/cancel").await.assert_redirect(); app.assert_database_has("imports", json!({ "id": 7, "status": "failed" })).await; app.assert_database_missing("imports", json!({ "id": 7, "failed_at": null })).await; app.assert_database_empty("import_chunks").await;}| Assertion | Asserts |
|---|---|
assert_database_has(table, columns) |
That a row has all the given column values |
assert_database_missing(table, columns) |
That no row has all the given column values |
assert_database_count(table, count) |
That the table has exactly count rows |
assert_database_empty(table) |
That the table has no rows |
assert_model_exists(&model) |
That the model's table has a row with the model's key |
assert_model_missing(&model) |
That the model's table has no row with the model's key |
null matches SQL NULL, and numbers and booleans match however the database stores them. Write dates and times in the database's own text format: PostgreSQL writes a timestamptz as 2026-10-23 12:00:00+00, and MySQL writes a DATETIME as 2026-10-23 12:00:00. When assert_database_has fails, it shows the rows that came closest, in that format.
To read a connection other than the default, name it with connection, as in app.assert_database_count("audits", 1).connection("reporting").await.
You can also query models directly inside a test and check their fields with standard assertions like assert_eq! and assert!, which is often cleaner when verifying enums, dates, or computed values:
let import = Import::find_or_fail(import.id).await?;assert_eq!(import.status, "failed");assert!(import.failed_at.is_some());Fakes
Instead of hitting external APIs, sending real emails, or running external processes in your tests, dust-framework provides built-in fakes that intercept calls and record them for assertions. Each fake() function returns a guard handle that stays active until dropped, so bind it to a variable (such as let mail = mail::fake();) rather than discarding it with let _ = ....
Check out each subsystem's testing guide for its fake and assertion API:
- Broadcasting (
broadcast::fake) - Events (
event::fake) - Feature flags (
feature::fake) - File storage (
storage::fake) - HTTP client (
client::fake) - Mail (
mail::fake) - Notifications (
notification::fake) - Processes (
process::fake) - Queues (
queue::fake) - SMS (
sms::fake)
Swapping services
To test code that interacts with an external system, such as a payment gateway, swap the real service in the container for a fake. For example, suppose your checkout handler injects a Stripe service:
use app::services::Stripe;use dust::prelude::*;pub async fn store(stripe: Inject<Stripe>) -> dust::Result<Redirect> { stripe.charge(2_000).await?; Ok(Redirect::to("/orders"))}You can give Stripe a fake constructor that records charges in memory instead of calling the Stripe API:
// src/services/stripe.rsuse std::sync::Mutex;pub struct Stripe { mode: Mode,}enum Mode { Live { api_key: String }, Fake(Mutex<Vec<u64>>),}impl Stripe { pub fn fake() -> Self { Self { mode: Mode::Fake(Mutex::default()) } } pub async fn charge(&self, cents: u64) -> dust::Result<()> { match &self.mode { Mode::Live { api_key } => { // Send the charge request to Stripe... Ok(()) } Mode::Fake(charges) => { charges.lock().unwrap().push(cents); Ok(()) } } } pub fn assert_charged(&self, cents: u64) { let Mode::Fake(charges) = &self.mode else { panic!("Stripe is not faked"); }; assert!(charges.lock().unwrap().contains(¢s)); }}In your test, app.swap replaces the service in the container and returns an Arc<Stripe> handle for assertions:
use app::services::Stripe;use dust::testing::prelude::*;#[dust::test]async fn checkout_charges_the_customer(app: Application) { let stripe = app.swap(Stripe::fake()); app.post("/checkout").await.assert_redirect(); stripe.assert_charged(2_000);}Be sure to swap the service before sending any requests that resolve it.
When your handlers take a trait contract, such as Inject<dyn Geocoder>, your fake can be a small struct of its own that implements the trait. Keep your own Arc of it for your assertions, and swap it in with swap_as. This fake geocoder returns fixed coordinates and records each address it's asked about, so the test never calls the real geocoding service:
use std::sync::{Arc, Mutex};use app::services::geocoder::{Coordinates, Geocoder};use async_trait::async_trait;use dust::testing::prelude::*;#[derive(Default)]struct FakeGeocoder { addresses: Mutex<Vec<String>>,}#[async_trait]impl Geocoder for FakeGeocoder { async fn locate(&self, address: &str) -> dust::Result<Coordinates> { self.addresses.lock().unwrap().push(address.to_owned()); Ok(Coordinates { latitude: 41.8781, longitude: -87.6298 }) }}#[dust::test]async fn stores_are_found_near_the_address(app: Application) { let geocoder = Arc::new(FakeGeocoder::default()); app.swap_as(Arc::clone(&geocoder) as Arc<dyn Geocoder>); app.get("/stores?address=Chicago").await.assert_ok(); assert_eq!(*geocoder.addresses.lock().unwrap(), ["Chicago"]);}Time travel
To test time-dependent behavior, such as an invitation expiring, advance your application's clock instead of sleeping. For example, suppose invitation links expire after 24 hours:
use dust::testing::prelude::*;#[dust::test]async fn invitations_expire_after_a_day(app: Application) { let invitation = app.post("/invitations").await; let link = invitation.json()["link"].as_str().unwrap().to_owned(); app.travel(25.hours()); app.get(&link).await.assert_forbidden();}travel takes a span in any unit, such as 25.hours() or 1.month(). After it travels, the application's time stands still until you call travel_back. You may also call these methods:
travel_to(time)travels to a time, such as aZonedDateTimeor aTimestamp.freeze_time()stops time where it is.freeze_second()stops time at the start of the current second, so a time your test compares with one the database stored to the second matches exactly.travel_back()returns to the present.
Each test application maintains an isolated clock, so concurrent tests never shift each other's time. Read the current time with dust::now() rather than ZonedDateTime::now() or SystemTime::now() so tests can control it.
Testing without requests
Some code is easier to test by invoking it directly rather than through an HTTP request. Because a test accepting Application runs inside the application context, you can call your own functions and resolve services with app.resolve::<T>(), returning the same instance your handlers receive. For example, suppose your application registers a Cart service with a count method:
use dust::testing::prelude::*;#[dust::test]async fn the_cart_starts_empty(app: Application) { let cart = app.resolve::<Cart>().await; assert_eq!(cart.count(), 0);}Testing console commands
Call app.command(...) to execute a console command, capture its output, and assert on both the exit status and output streams:
use dust::testing::prelude::*;#[dust::test]async fn newsletters_can_be_sent(app: Application) { app.command("newsletter:send --queue=high") .await .assert_successful() .assert_error_output_contains("Sent.");}Status messages such as console.success write to stderr, so verify them with assert_error_output_contains. Verify stdout output (from line and tables) with assert_output_contains. You may also assert absence with assert_output_missing, assert_error_output_missing, and assert_no_output.
To simulate interactive user input, chain expects_question, expects_confirmation, or other expects_ helpers before awaiting the command. To learn more, check out Testing commands in the console guide.
Troubleshooting tests
| Symptom | What to check |
|---|---|
no such table on the first query |
refresh_database is enabled in src/testing.rs, and the test database exists. |
permission denied to create database |
The test user needs CREATEDB on PostgreSQL or CREATE on MySQL; create the numbered copies by hand once to see the exact grant. |
| A test passes alone but fails in the suite | It depends on state another test left behind. Give it its own factory rows, or reset the value it assumes. |
travel has no effect |
The code reads ZonedDateTime::now() or SystemTime::now() instead of dust::now(). |
| A fake is never called | The fake guard was dropped or bound to _; bind it to a named variable that lives to the end of the test. |
| A swapped service isn't used | swap ran after the request that resolved the service, or the handler asks for a different type. |
| A queued job didn't run | In the testing environment jobs go to the default connection, but a test that fakes the queue only records them. Check which fake is active. |
404 for a route that exists |
The route belongs to the api group and the test used a web URL, or the application under test didn't register that route file. |
| A redirect assertion fails | The handler flashed errors or returned back(); pass from(...) so the test client knows the previous page. |
Output from println! is missing |
Cargo hides it for passing tests; run with -- --nocapture. |
A failing assertion prints the response body and headers. When the body is HTML, pipe the test output through a pager or write the response to a file with response.text() while you debug. Remove that code before committing.