Testing
- Introduction
- Writing tests
- Configuring your tests
- Making requests
- Available assertions
- Testing JSON APIs
- Testing Inertia pages
- Testing views
- Testing head metadata
- Testing errors
- Testing the database
- Fakes
- Swapping services
- Time travel
- Testing without requests
- Testing console commands
Introduction
Laravel 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:
1use laravel::testing::prelude::*;23#[laravel::test]4async fn the_application_returns_a_successful_response(app: Application) {5 app.get("/").await.assert_ok();6}1use laravel::testing::prelude::*;23#[laravel::test]4async fn the_application_returns_a_successful_response(app: Application) {5 app.get("/").await.assert_ok();6}
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.
laravel::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 #[laravel::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:
1use laravel::testing::prelude::*;23#[laravel::test]4fn titles_become_slugs() {5 assert_eq!("Laravel Is Here!".slug(), "laravel-is-here");6}1use laravel::testing::prelude::*;23#[laravel::test]4fn titles_become_slugs() {5 assert_eq!("Laravel Is Here!".slug(), "laravel-is-here");6}
For general value assertions, use Rust's built-in assert!, assert_eq!, and assert_ne! macros:
1assert!(user.is_admin);2assert!(!user.is_suspended);3assert_eq!(invoice.total, 12_000);1assert!(user.is_admin);2assert!(!user.is_suspended);3assert_eq!(invoice.total, 12_000);
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 laravel::config() directly. Name the argument _app when you only need those functions:
1use laravel::crypt;2use laravel::testing::prelude::*;34#[laravel::test]5fn secrets_can_be_decrypted(_app: Application) -> laravel::Result<()> {6 let payload = crypt::encrypt_string("secret")?;78 assert_eq!(crypt::decrypt_string(&payload)?, "secret");910 Ok(())11}1use laravel::crypt;2use laravel::testing::prelude::*;34#[laravel::test]5fn secrets_can_be_decrypted(_app: Application) -> laravel::Result<()> {6 let payload = crypt::encrypt_string("secret")?;78 assert_eq!(crypt::decrypt_string(&payload)?, "secret");910 Ok(())11}
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:
1cargo test23cargo test invitations1cargo test23cargo test invitations
Cargo 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.
Configuring your tests
Application tests call app::testing::create, defined in src/testing.rs. 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 applies the test overrides listed in src/testing.rs:
1use laravel::Application;2use laravel::foundation::ApplicationBuilder;34pub fn create() -> Application {5 configure().create()6}78pub fn configure() -> ApplicationBuilder {9 crate::configure()10 .for_testing(env!("CARGO_MANIFEST_DIR"))11 .with_envs([12 ("APP_ENV", "testing"),13 ("APP_DEBUG", "true"),14 ("BCRYPT_ROUNDS", "4"),15 ("BROADCAST_CONNECTION", "discard"),16 ("CACHE_STORE", "memory"),17 ("FEATURE_STORE", "memory"),18 ("INERTIA_SSR", "false"),19 ("MAIL_MAILER", "log"),20 ("OTEL_SDK_DISABLED", "true"),21 ("QUEUE_CONNECTION", "sync"),22 ("SESSION_DRIVER", "memory"),23 ("SMS_SENDER", "log"),24 ("WORKFLOW_STORE", "memory"),25 ])26 .refresh_database()27}1use laravel::Application;2use laravel::foundation::ApplicationBuilder;34pub fn create() -> Application {5 configure().create()6}78pub fn configure() -> ApplicationBuilder {9 crate::configure()10 .for_testing(env!("CARGO_MANIFEST_DIR"))11 .with_envs([12 ("APP_ENV", "testing"),13 ("APP_DEBUG", "true"),14 ("BCRYPT_ROUNDS", "4"),15 ("BROADCAST_CONNECTION", "discard"),16 ("CACHE_STORE", "memory"),17 ("FEATURE_STORE", "memory"),18 ("INERTIA_SSR", "false"),19 ("MAIL_MAILER", "log"),20 ("OTEL_SDK_DISABLED", "true"),21 ("QUEUE_CONNECTION", "sync"),22 ("SESSION_DRIVER", "memory"),23 ("SMS_SENDER", "log"),24 ("WORKFLOW_STORE", "memory"),25 ])26 .refresh_database()27}
Any variable in .env that isn't overridden in src/testing.rs, such as DATABASE_URL or your application's own API keys, takes effect as usual. If a variable in .env is missing or empty, such as APP_KEY in CI without a .env file, for_testing fills in a fresh APP_KEY and the same fast, in-memory fallbacks 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 an override above, such as testing against a Redis cache configured in .env, remove that line from with_envs.
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:
1use laravel::testing::prelude::*;23fn app_in_euros() -> Application {4 app::testing::configure().with_env("BILLING_CURRENCY", "eur").create()5}67#[laravel::test(app = app_in_euros)]8async fn prices_are_shown_in_euros(app: Application) {9 app.get("/pricing").await.assert_see("€");10}1use laravel::testing::prelude::*;23fn app_in_euros() -> Application {4 app::testing::configure().with_env("BILLING_CURRENCY", "eur").create()5}67#[laravel::test(app = app_in_euros)]8async fn prices_are_shown_in_euros(app: Application) {9 app.get("/pricing").await.assert_see("€");10}
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 laravel::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:
1use laravel::testing::prelude::*;23#[laravel::test]4async fn posts_are_listed(app: Application) {5 app.get("/posts").await.assert_ok().assert_see("Posts");6}1use laravel::testing::prelude::*;23#[laravel::test]4async fn posts_are_listed(app: Application) {5 app.get("/posts").await.assert_ok().assert_see("Posts");6}
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:
1app.get("/users")2 .header("accept", "application/json")3 .header("accept-language", "fr")4 .await5 .assert_ok();1app.get("/users")2 .header("accept", "application/json")3 .header("accept-language", "fr")4 .await5 .assert_ok();
To authenticate an API request with a bearer token, call token, which sets the Authorization header:
1app.get("/api/me").token("my-api-token").await.assert_ok();1app.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:
1app.post("/login").with_ip([203, 0, 113, 7]).await.assert_redirect();1app.post("/login").with_ip([203, 0, 113, 7]).await.assert_redirect();
Sending input
Use form to submit form fields to web and Inertia routes as a browser does (so validation failures redirect back with errors), or json to send a JSON payload to API endpoints with the Accept: application/json header:
1use laravel::testing::prelude::*;23#[laravel::test]4async fn users_can_sign_up(app: Application) {5 app.post("/sign-up")6 .form([7 ("name", "Taylor"),9 ("password", "secret123"),10 ("password_confirmation", "secret123"),11 ])12 .await13 .assert_redirect_to("/dashboard");1415 app.post("/api/users")17 .await18 .assert_created();19}1use laravel::testing::prelude::*;23#[laravel::test]4async fn users_can_sign_up(app: Application) {5 app.post("/sign-up")6 .form([7 ("name", "Taylor"),9 ("password", "secret123"),10 ("password_confirmation", "secret123"),11 ])12 .await13 .assert_redirect_to("/dashboard");1415 app.post("/api/users")17 .await18 .assert_created();19}
To send a raw request body verbatim, such as a signed webhook payload, use body together with header for the content type:
1app.post("/webhooks/stripe")2 .header("content-type", "application/json")3 .body(r#"{"type": "invoice.paid"}"#)4 .await5 .assert_ok();1app.post("/webhooks/stripe")2 .header("content-type", "application/json")3 .body(r#"{"type": "invoice.paid"}"#)4 .await5 .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:
1use laravel::http::client::Attachment;23app.post("/avatar")4 .attach("avatar", Attachment::from_path("tests/fixtures/taylor.png"))5 .form([("name", "Taylor")])6 .await7 .assert_ok();1use laravel::http::client::Attachment;23app.post("/avatar")4 .attach("avatar", Attachment::from_path("tests/fixtures/taylor.png"))5 .form([("name", "Taylor")])6 .await7 .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):
1app.post("/avatar")2 .attach("avatar", Attachment::fake_image("taylor.png", 640, 480))3 .await4 .assert_ok();56app.post("/documents")7 .attach("document", Attachment::fake("report.pdf", 6_000))8 .await9 .assert_invalid(&["document"]);1app.post("/avatar")2 .attach("avatar", Attachment::fake_image("taylor.png", 640, 480))3 .await4 .assert_ok();56app.post("/documents")7 .attach("document", Attachment::fake("report.pdf", 6_000))8 .await9 .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:
1let first = app.post("/settings/theme").form([("theme", "dark")]).await;23app.get("/settings")4 .with_cookies_from(&first)5 .await6 .assert_see("Dark theme");1let first = app.post("/settings/theme").form([("theme", "dark")]).await;23app.get("/settings")4 .with_cookies_from(&first)5 .await6 .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:
1app.post("/checkout")2 .with_session(json!({ "coupon": "WELCOME10" }))3 .await4 .assert_redirect_to("/orders")5 .assert_session_has("status", "Order placed!")6 .assert_session_missing("coupon");1app.post("/checkout")2 .with_session(json!({ "coupon": "WELCOME10" }))3 .await4 .assert_redirect_to("/orders")5 .assert_session_has("status", "Order placed!")6 .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:
1app.post("/cart")2 .form([("product", "7")])3 .await4 .assert_session_present("cart")5 .assert_session_where("cart", |cart: Vec<u64>| cart.contains(&7));1app.post("/cart")2 .form([("product", "7")])3 .await4 .assert_session_present("cart")5 .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). Laravel 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:
1app.get("/").cookie("theme", "dark").await.assert_see("dark");23app.post("/theme")4 .form([("theme", "dark")])5 .await6 .assert_cookie("theme", "dark");78app.post("/tour/dismiss").await.assert_cookie_expired("tour");1app.get("/").cookie("theme", "dark").await.assert_see("dark");23app.post("/theme")4 .form([("theme", "dark")])5 .await6 .assert_cookie("theme", "dark");78app.post("/tour/dismiss").await.assert_cookie_expired("tour");
Acting as a user
To send a request as a logged-in user, use acting_as:
1use laravel::model::create;2use laravel::testing::prelude::*;34#[laravel::test]5async fn users_see_their_dashboard(app: Application) -> laravel::Result<()> {6 let user = create!(User {7 name: "Taylor",9 password: "password",10 })11 .await?;1213 app.get("/dashboard").acting_as(&user).await.assert_ok();1415 Ok(())16}1use laravel::model::create;2use laravel::testing::prelude::*;34#[laravel::test]5async fn users_see_their_dashboard(app: Application) -> laravel::Result<()> {6 let user = create!(User {7 name: "Taylor",9 password: "password",10 })11 .await?;1213 app.get("/dashboard").acting_as(&user).await.assert_ok();1415 Ok(())16}
To verify authentication state after a login, registration, or logout request, use assert_authenticated, assert_authenticated_as(&user), or assert_guest:
1app.post("/login")3 .await4 .assert_redirect_to("/dashboard")5 .assert_authenticated_as(&user);67app.post("/login")9 .await10 .assert_guest();1app.post("/login")3 .await4 .assert_redirect_to("/dashboard")5 .assert_authenticated_as(&user);67app.post("/login")9 .await10 .assert_guest();
Following redirects
To test the page that a form redirects to, call follow_redirects:
1app.post("/posts")2 .form([("title", "Hello")])3 .follow_redirects()4 .await5 .assert_ok()6 .assert_see("Post created!");1app.post("/posts")2 .form([("title", "Hello")])3 .follow_redirects()4 .await5 .assert_ok()6 .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:
1use laravel::testing::prelude::*;23#[laravel::test]4async fn sign_ups_need_a_valid_email(app: Application) {5 app.post("/sign-up")6 .from("/sign-up")7 .form([("name", "Taylor"), ("email", "taylor"), ("password", "secret123")])8 .await9 .assert_redirect_back_with_errors(&["email"])10 .assert_session_has_input("email", "taylor")11 .assert_session_missing_input("password");12}1use laravel::testing::prelude::*;23#[laravel::test]4async fn sign_ups_need_a_valid_email(app: Application) {5 app.post("/sign-up")6 .from("/sign-up")7 .form([("name", "Taylor"), ("email", "taylor"), ("password", "secret123")])8 .await9 .assert_redirect_back_with_errors(&["email"])10 .assert_session_has_input("email", "taylor")11 .assert_session_missing_input("password");12}
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 assertion on TestResponse borrows and returns the response so you can chain multiple checks together. In addition to the assertions below, dedicated sections cover cookies and sessions, authentication, JSON, Inertia, views, head metadata, and errors.
Status assertions
Use assert_status with a status code number or StatusCode, or call one of the named helpers for common HTTP statuses:
1app.get("/posts").await.assert_ok();2app.post("/api/posts").json(json!({ "title": "Hello" })).await.assert_created();3app.delete("/api/posts/1").await.assert_no_content();4app.get("/missing").await.assert_not_found();5app.get("/custom").await.assert_status(418);1app.get("/posts").await.assert_ok();2app.post("/api/posts").json(json!({ "title": "Hello" })).await.assert_created();3app.delete("/api/posts/1").await.assert_no_content();4app.get("/missing").await.assert_not_found();5app.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 with an empty body |
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:
1app.post("/posts")2 .form([("title", "Hello")])3 .await4 .assert_redirect_to(route!(posts::index)?);56app.post("/orders")7 .form([("plan", "pro")])8 .await9 .assert_redirect_to(route!(orders::show, &order)?);1011app.post("/invitations")13 .await14 .assert_redirect_to_signed_route(invitations::accept, &invitation);1app.post("/posts")2 .form([("title", "Hello")])3 .await4 .assert_redirect_to(route!(posts::index)?);56app.post("/orders")7 .form([("plan", "pro")])8 .await9 .assert_redirect_to(route!(orders::show, &order)?);1011app.post("/invitations")13 .await14 .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, |
A redirect to the route of a handler |
assert_redirect_to_signed_route(handler, |
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:
1app.get("/api/posts")2 .await3 .assert_header("x-request-id", "req_123")4 .assert_header_contains("cache-control", "no-store")5 .assert_header_present("etag")6 .assert_header_missing("x-powered-by");78app.get("/invoices/1/download")9 .await10 .assert_ok()11 .assert_download("invoice-1.pdf");1app.get("/api/posts")2 .await3 .assert_header("x-request-id", "req_123")4 .assert_header_contains("cache-control", "no-store")5 .assert_header_present("etag")6 .assert_header_missing("x-powered-by");78app.get("/invoices/1/download")9 .await10 .assert_ok()11 .assert_download("invoice-1.pdf");
| Method | Asserts |
|---|---|
assert_header(name,, assert_header_contains(name, |
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:
1app.get("/posts")2 .await3 .assert_ok()4 .assert_see("Taylor's Post")5 .assert_dont_see("Draft Post")6 .assert_see_in_order(&["First Post", "Second Post"])7 .assert_see_html("<h1>Posts</h1>");1app.get("/posts")2 .await3 .assert_ok()4 .assert_see("Taylor's Post")5 .assert_dont_see("Draft Post")6 .assert_see_in_order(&["First Post", "Second Post"])7 .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:
1app.post("/sign-up")2 .form([("name", "Taylor"), ("email", "not-an-email")])3 .await4 .assert_invalid(&["email", "password"])5 .assert_valid(&["name"])6 .assert_invalid_messages(&[("email", "valid email")]);78app.post("/settings/password")9 .form([("password", "short")])10 .await11 .assert_invalid_in("password", &["password"]);1app.post("/sign-up")2 .form([("name", "Taylor"), ("email", "not-an-email")])3 .await4 .assert_invalid(&["email", "password"])5 .assert_valid(&["name"])6 .assert_invalid_messages(&[("email", "valid email")]);78app.post("/settings/password")9 .form([("password", "short")])10 .await11 .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, |
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:
1let response = app.get("/posts").await;23response.assert_ok().assert_see("Posts");45println!("{}", response.text());1let response = app.get("/posts").await;23response.assert_ok().assert_see("Posts");45println!("{}", 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 Laravel 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:
1{2 "data": [5 ],6 "meta": { "total": 2 }7}1{2 "data": [5 ],6 "meta": { "total": 2 }7}
You only need to specify the keys you want to verify:
1use laravel::testing::prelude::*;23#[laravel::test]4async fn users_are_listed(app: Application) {5 app.get("/api/users")6 .await7 .assert_ok()8 .assert_json(json!({9 "data": [10 { "name": "Taylor" },11 { "name": "Abigail" },12 ],13 }));14}1use laravel::testing::prelude::*;23#[laravel::test]4async fn users_are_listed(app: Application) {5 app.get("/api/users")6 .await7 .assert_ok()8 .assert_json(json!({9 "data": [10 { "name": "Taylor" },11 { "name": "Abigail" },12 ],13 }));14}
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:
1app.get("/api/users")2 .await3 .assert_json_path("data.0.name", "Taylor")4 .assert_json_count_at("data", 2);1app.get("/api/users")2 .await3 .assert_json_path("data.0.name", "Taylor")4 .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:
1app.get("/api/users")2 .await3 .assert_json_path_where("meta.total", |total: u64| total >= 2)4 .assert_json_missing_path("data.0.password");1app.get("/api/users")2 .await3 .assert_json_path_where("meta.total", |total: u64| total >= 2)4 .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:
1app.get("/api/users")2 .await3 .assert_json_fragment(json!({ "name": "Taylor", "role": "admin" }))4 .assert_json_missing(json!({ "name": "Jess" }));1app.get("/api/users")2 .await3 .assert_json_fragment(json!({ "name": "Taylor", "role": "admin" }))4 .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:
1app.get("/api/users")2 .await3 .assert_json_structure(json!({4 "data": { "*": ["id", "name", { "team": ["id", "name"] }] },5 "meta": ["total"],6 }));1app.get("/api/users")2 .await3 .assert_json_structure(json!({4 "data": { "*": ["id", "name", { "team": ["id", "name"] }] },5 "meta": ["total"],6 }));
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():
1use laravel::testing::prelude::*;23#[laravel::test]4async fn users_are_shown_without_their_password(app: Application) {5 app.get("/api/users/1").await.assert_json_matches(|json| {6 json.equals("id", 1)7 .equals("name", "Taylor")8 .missing("password")9 .scope("team", |team| team.has("id").etc())10 });11}1use laravel::testing::prelude::*;23#[laravel::test]4async fn users_are_shown_without_their_password(app: Application) {5 app.get("/api/users/1").await.assert_json_matches(|json| {6 json.equals("id", 1)7 .equals("name", "Taylor")8 .missing("password")9 .scope("team", |team| team.has("id").etc())10 });11}
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:
1app.get("/api/users").await.assert_json_matches(|json| {2 json.has_count("data", 2)3 .first("data", |user| user.equals("name", "Taylor").etc())4 .each("data", |user| user.satisfies("id", |id: u64| id > 0).missing("password").etc())5 .etc()6});1app.get("/api/users").await.assert_json_matches(|json| {2 json.has_count("data", 2)3 .first("data", |user| user.equals("name", "Taylor").etc())4 .each("data", |user| user.satisfies("id", |id: u64| id > 0).missing("password").etc())5 .etc()6});
| 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, |
The value at a path |
satisfies(path, |
That the value at a path passes your check, read as the closure's argument type |
contains(path, |
That a list item or object value equals item in full |
has_count(path,, has_count_in(path, |
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 Inertia pages
To test an Inertia page, call assert_inertia, then assert on the page's component and props:
1app.get("/users/1")2 .await3 .assert_inertia()4 .component("Users/Show")5 .has("user")6 .equals("user.name", "Taylor")7 .missing("user.password");1app.get("/users/1")2 .await3 .assert_inertia()4 .component("Users/Show")5 .has("user")6 .equals("user.name", "Taylor")7 .missing("user.password");
For the full list of Inertia page assertions and partial reload testing, check out testing pages in the Inertia guide.
Testing views
A response that rendered a view records the view's name and the template data passed to it:
1use laravel::model::create;2use laravel::testing::prelude::*;34#[laravel::test]5async fn the_user_list_shows_each_user(app: Application) -> laravel::Result<()> {78 app.get("/users")9 .await10 .assert_view_is("users.index")11 .assert_view_has("users.0.name", "Taylor");1213 Ok(())14}1use laravel::model::create;2use laravel::testing::prelude::*;34#[laravel::test]5async fn the_user_list_shows_each_user(app: Application) -> laravel::Result<()> {78 app.get("/users")9 .await10 .assert_view_is("users.index")11 .assert_view_has("users.0.name", "Taylor");1213 Ok(())14}
Testing head metadata
assert_head reads a response's head metadata, whether it's an HTML page or an Inertia page:
1app.get("/posts/1")2 .await3 .assert_head()4 .title("Hello World · Laravel")5 .meta("og:title", "Hello World · Laravel")6 .missing("robots");1app.get("/posts/1")2 .await3 .assert_head()4 .title("Hello World · Laravel")5 .meta("og:title", "Hello World · Laravel")6 .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:
1app.post("/checkout").await.assert_payment_required().assert_error::<PaymentFailed>();23app.post("/checkout")4 .await5 .assert_error_where(|error: &PaymentFailed| error.reason == "insufficient funds");1app.post("/checkout").await.assert_payment_required().assert_error::<PaymentFailed>();23app.post("/checkout")4 .await5 .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 laravel::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. Laravel 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 (new applications include it by default). 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:
1use laravel::foundation::ApplicationBuilder;23pub fn configure() -> ApplicationBuilder {4 crate::configure()5 .for_testing(env!("CARGO_MANIFEST_DIR"))7 .refresh_database()8}1use laravel::foundation::ApplicationBuilder;23pub fn configure() -> ApplicationBuilder {4 crate::configure()5 .for_testing(env!("CARGO_MANIFEST_DIR"))7 .refresh_database()8}
Each test borrows a numbered copy of that database, such as laravel_test_1, that no other running test uses, so tests run in parallel. Laravel 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, Laravel 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:
1touch src/app.rs && cargo test1touch src/app.rs && cargo test
Each 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. Laravel 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:
1let user = User::factory().create().await?;23let posts = Post::factory()4 .for_(Post::user, &user)5 .count(3)6 .create()7 .await?;1let user = User::factory().create().await?;23let posts = Post::factory()4 .for_(Post::user, &user)5 .count(3)6 .create()7 .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:
1use app::seeders;2use laravel::testing::prelude::*;34#[laravel::test]5async fn the_archive_lists_every_post(app: Application) -> laravel::Result<()> {6 app.seed(seeders::posts).await;78 app.get("/archive").await.assert_ok().assert_see("Archive");910 Ok(())11}1use app::seeders;2use laravel::testing::prelude::*;34#[laravel::test]5async fn the_archive_lists_every_post(app: Application) -> laravel::Result<()> {6 app.seed(seeders::posts).await;78 app.get("/archive").await.assert_ok().assert_see("Archive");910 Ok(())11}
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:
1pub fn configure() -> ApplicationBuilder {2 crate::configure()3 .for_testing(env!("CARGO_MANIFEST_DIR"))4 .refresh_database()5 .seed_once(crate::seeders::roles)6}1pub fn configure() -> ApplicationBuilder {2 crate::configure()3 .for_testing(env!("CARGO_MANIFEST_DIR"))4 .refresh_database()5 .seed_once(crate::seeders::roles)6}
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:
1fn app_with_posts() -> Application {2 app::testing::configure().seed(app::seeders::posts).create()3}45#[laravel::test(app = app_with_posts)]6async fn the_archive_paginates(app: Application) {7 app.get("/archive?page=2").await.assert_ok();8}1fn app_with_posts() -> Application {2 app::testing::configure().seed(app::seeders::posts).create()3}45#[laravel::test(app = app_with_posts)]6async fn the_archive_paginates(app: Application) {7 app.get("/archive?page=2").await.assert_ok();8}
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:
1use laravel::testing::prelude::*;23#[laravel::test]4async fn cancelling_an_import_fails_it(app: Application) {5 app.post("/imports/7/cancel").await.assert_redirect();67 app.assert_database_has("imports", json!({ "id": 7, "status": "failed" })).await;8 app.assert_database_missing("imports", json!({ "id": 7, "failed_at": null })).await;9 app.assert_database_empty("import_chunks").await;10}1use laravel::testing::prelude::*;23#[laravel::test]4async fn cancelling_an_import_fails_it(app: Application) {5 app.post("/imports/7/cancel").await.assert_redirect();67 app.assert_database_has("imports", json!({ "id": 7, "status": "failed" })).await;8 app.assert_database_missing("imports", json!({ "id": 7, "failed_at": null })).await;9 app.assert_database_empty("import_chunks").await;10}
| Assertion | Asserts |
|---|---|
assert_database_has(table, |
That a row has all the given column values |
assert_database_missing(table, |
That no row has all the given column values |
assert_database_count(table, |
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:
1let import = Import::find_or_fail(import.id).await?;23assert_eq!(import.status, "failed");4assert!(import.failed_at.is_some());1let import = Import::find_or_fail(import.id).await?;23assert_eq!(import.status, "failed");4assert!(import.failed_at.is_some());
Fakes
Instead of hitting external APIs, sending real emails, or running external processes in your tests, Laravel 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:
1use app::services::Stripe;2use laravel::prelude::*;34pub async fn store(stripe: Inject<Stripe>) -> laravel::Result<Redirect> {5 stripe.charge(2_000).await?;67 Ok(Redirect::to("/orders"))8}1use app::services::Stripe;2use laravel::prelude::*;34pub async fn store(stripe: Inject<Stripe>) -> laravel::Result<Redirect> {5 stripe.charge(2_000).await?;67 Ok(Redirect::to("/orders"))8}
You can give Stripe a fake constructor that records charges in memory instead of calling the Stripe API:
1// src/services/stripe.rs2use std::sync::Mutex;34pub struct Stripe {5 mode: Mode,6}78enum Mode {9 Live { api_key: String },10 Fake(Mutex<Vec<u64>>),11}1213impl Stripe {14 pub fn fake() -> Self {15 Self { mode: Mode::Fake(Mutex::default()) }16 }1718 pub async fn charge(&self, cents: u64) -> laravel::Result<()> {19 match &self.mode {20 Mode::Live { api_key } => {21 // Send the charge request to Stripe...22 Ok(())23 }24 Mode::Fake(charges) => {25 charges.lock().unwrap().push(cents);26 Ok(())27 }28 }29 }3031 pub fn assert_charged(&self, cents: u64) {32 let Mode::Fake(charges) = &self.mode else {33 panic!("Stripe is not faked");34 };3536 assert!(charges.lock().unwrap().contains(¢s));37 }38}1// src/services/stripe.rs2use std::sync::Mutex;34pub struct Stripe {5 mode: Mode,6}78enum Mode {9 Live { api_key: String },10 Fake(Mutex<Vec<u64>>),11}1213impl Stripe {14 pub fn fake() -> Self {15 Self { mode: Mode::Fake(Mutex::default()) }16 }1718 pub async fn charge(&self, cents: u64) -> laravel::Result<()> {19 match &self.mode {20 Mode::Live { api_key } => {21 // Send the charge request to Stripe...22 Ok(())23 }24 Mode::Fake(charges) => {25 charges.lock().unwrap().push(cents);26 Ok(())27 }28 }29 }3031 pub fn assert_charged(&self, cents: u64) {32 let Mode::Fake(charges) = &self.mode else {33 panic!("Stripe is not faked");34 };3536 assert!(charges.lock().unwrap().contains(¢s));37 }38}
In your test, app.swap replaces the service in the container and returns an Arc<Stripe> handle for assertions:
1use app::services::Stripe;2use laravel::testing::prelude::*;34#[laravel::test]5async fn checkout_charges_the_customer(app: Application) {6 let stripe = app.swap(Stripe::fake());78 app.post("/checkout").await.assert_redirect();910 stripe.assert_charged(2_000);11}1use app::services::Stripe;2use laravel::testing::prelude::*;34#[laravel::test]5async fn checkout_charges_the_customer(app: Application) {6 let stripe = app.swap(Stripe::fake());78 app.post("/checkout").await.assert_redirect();910 stripe.assert_charged(2_000);11}
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:
1use std::sync::{Arc, Mutex};23use app::services::geocoder::{Coordinates, Geocoder};4use async_trait::async_trait;5use laravel::testing::prelude::*;67#[derive(Default)]8struct FakeGeocoder {9 addresses: Mutex<Vec<String>>,10}1112#[async_trait]13impl Geocoder for FakeGeocoder {14 async fn locate(&self, address: &str) -> laravel::Result<Coordinates> {15 self.addresses.lock().unwrap().push(address.to_owned());1617 Ok(Coordinates { latitude: 41.8781, longitude: -87.6298 })18 }19}2021#[laravel::test]22async fn stores_are_found_near_the_address(app: Application) {23 let geocoder = Arc::new(FakeGeocoder::default());2425 app.swap_as(Arc::clone(&geocoder) as Arc<dyn Geocoder>);2627 app.get("/stores?address=Chicago").await.assert_ok();2829 assert_eq!(*geocoder.addresses.lock().unwrap(), ["Chicago"]);30}1use std::sync::{Arc, Mutex};23use app::services::geocoder::{Coordinates, Geocoder};4use async_trait::async_trait;5use laravel::testing::prelude::*;67#[derive(Default)]8struct FakeGeocoder {9 addresses: Mutex<Vec<String>>,10}1112#[async_trait]13impl Geocoder for FakeGeocoder {14 async fn locate(&self, address: &str) -> laravel::Result<Coordinates> {15 self.addresses.lock().unwrap().push(address.to_owned());1617 Ok(Coordinates { latitude: 41.8781, longitude: -87.6298 })18 }19}2021#[laravel::test]22async fn stores_are_found_near_the_address(app: Application) {23 let geocoder = Arc::new(FakeGeocoder::default());2425 app.swap_as(Arc::clone(&geocoder) as Arc<dyn Geocoder>);2627 app.get("/stores?address=Chicago").await.assert_ok();2829 assert_eq!(*geocoder.addresses.lock().unwrap(), ["Chicago"]);30}
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:
1use laravel::testing::prelude::*;23#[laravel::test]4async fn invitations_expire_after_a_day(app: Application) {5 let invitation = app.post("/invitations").await;67 let link = invitation.json()["link"].as_str().unwrap().to_owned();89 app.travel(25.hours());1011 app.get(&link).await.assert_forbidden();12}1use laravel::testing::prelude::*;23#[laravel::test]4async fn invitations_expire_after_a_day(app: Application) {5 let invitation = app.post("/invitations").await;67 let link = invitation.json()["link"].as_str().unwrap().to_owned();89 app.travel(25.hours());1011 app.get(&link).await.assert_forbidden();12}
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 laravel::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:
1use laravel::testing::prelude::*;23#[laravel::test]4async fn the_cart_starts_empty(app: Application) {5 let cart = app.resolve::<Cart>().await;67 assert_eq!(cart.count(), 0);8}1use laravel::testing::prelude::*;23#[laravel::test]4async fn the_cart_starts_empty(app: Application) {5 let cart = app.resolve::<Cart>().await;67 assert_eq!(cart.count(), 0);8}
Testing console commands
Call app.command(...) to execute a console command, capture its output, and assert on both the exit status and output streams:
1use laravel::testing::prelude::*;23#[laravel::test]4async fn newsletters_can_be_sent(app: Application) {5 app.command("newsletter:send --queue=high")6 .await7 .assert_successful()8 .assert_error_output_contains("Sent.");9}1use laravel::testing::prelude::*;23#[laravel::test]4async fn newsletters_can_be_sent(app: Application) {5 app.command("newsletter:send --queue=high")6 .await7 .assert_successful()8 .assert_error_output_contains("Sent.");9}
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.