laravel-rust 0.1.3

Laravel for Rust: a full-stack Rust web framework.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
# Testing

- [Introduction]#introduction
- [Writing tests]#unit-and-application-tests
    - [Running tests]#running-tests
- [Configuring your tests]#configuring-your-tests
- [Making requests]#making-requests
    - [Customizing request headers]#customizing-request-headers
    - [Sending input]#sending-input
    - [Uploading files]#uploading-files
    - [Cookies and sessions]#cookies-and-sessions
    - [Acting as a user]#acting-as-a-user
    - [Following redirects]#following-redirects
    - [Redirecting back]#redirecting-back
- [Available assertions]#available-assertions
    - [Status assertions]#status-assertions
    - [Redirect assertions]#redirect-assertions
    - [Header and download assertions]#header-and-download-assertions
    - [Content assertions]#content-assertions
    - [Validation assertions]#validation-assertions
    - [Inspecting responses directly]#inspecting-responses-directly
- [Testing JSON APIs]#testing-json-apis
    - [Fluent JSON assertions]#fluent-json-assertions
- [Testing Inertia pages]#testing-inertia-pages
- [Testing views]#testing-views
- [Testing head metadata]#testing-head-metadata
- [Testing errors]#testing-errors
- [Testing the database]#testing-the-database
    - [Refreshing the database]#refreshing-the-database
    - [Seeding the database]#seeding-the-database
    - [Database assertions]#database-assertions
- [Fakes]#fakes
- [Swapping services]#swapping-services
- [Time travel]#time-travel
- [Testing without requests]#testing-without-requests
- [Testing console commands]#testing-console-commands

<a name="introduction"></a>
## 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:

```rust
use laravel::testing::prelude::*;

#[laravel::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.

`laravel::testing::prelude` imports everything from the [prelude](prelude.md) along with the test client traits on `Application` and the `json!` macro for building JSON payloads and assertions.

<a name="unit-and-application-tests"></a>
## 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:

```rust
use laravel::testing::prelude::*;

#[laravel::test]
fn titles_become_slugs() {
    assert_eq!("Laravel Is Here!".slug(), "laravel-is-here");
}
```

For general value assertions, use Rust's built-in `assert!`, `assert_eq!`, and `assert_ne!` macros:

```rust
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](#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:

```rust
use laravel::crypt;
use laravel::testing::prelude::*;

#[laravel::test]
fn secrets_can_be_decrypted(_app: Application) -> laravel::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.

<a name="running-tests"></a>
### Running tests

Run your tests with Cargo. To run only some of them, pass part of their names:

```shell
cargo test

cargo 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`](#refreshing-the-database), an isolated database, so tests never wait on each other.

<a name="configuring-your-tests"></a>
## 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`:

```rust
use laravel::Application;
use laravel::foundation::ApplicationBuilder;

pub fn create() -> Application {
    configure().create()
}

pub fn configure() -> ApplicationBuilder {
    crate::configure()
        .for_testing(env!("CARGO_MANIFEST_DIR"))
        .with_envs([
            ("APP_ENV", "testing"),
            ("APP_DEBUG", "true"),
            ("BCRYPT_ROUNDS", "4"),
            ("BROADCAST_CONNECTION", "discard"),
            ("CACHE_STORE", "memory"),
            ("FEATURE_STORE", "memory"),
            ("INERTIA_SSR", "false"),
            ("MAIL_MAILER", "log"),
            ("OTEL_SDK_DISABLED", "true"),
            ("QUEUE_CONNECTION", "sync"),
            ("SESSION_DRIVER", "memory"),
            ("SMS_SENDER", "log"),
            ("WORKFLOW_STORE", "memory"),
        ])
        .refresh_database()
}
```

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:

```rust
use laravel::testing::prelude::*;

fn app_in_euros() -> Application {
    app::testing::configure().with_env("BILLING_CURRENCY", "eur").create()
}

#[laravel::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 `laravel::config()`.

<a name="making-requests"></a>
## 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](#available-assertions):

```rust
use laravel::testing::prelude::*;

#[laravel::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](csrf.md) allows them through.

<a name="customizing-request-headers"></a>
### Customizing request headers

Use `header` to attach custom headers to a test request:

```rust
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:

```rust
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](middleware.md#trusting-proxies) or [rate limits](rate-limiting.md#testing), call `with_ip`:

```rust
app.post("/login").with_ip([203, 0, 113, 7]).await.assert_redirect();
```

<a name="sending-input"></a>
### Sending input

Use `form` to submit form fields to web and [Inertia](inertia.md) 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:

```rust
use laravel::testing::prelude::*;

#[laravel::test]
async fn users_can_sign_up(app: Application) {
    app.post("/sign-up")
        .form([
            ("name", "Taylor"),
            ("email", "taylor@laravel.com"),
            ("password", "secret123"),
            ("password_confirmation", "secret123"),
        ])
        .await
        .assert_redirect_to("/dashboard");

    app.post("/api/users")
        .json(json!({ "name": "Abigail", "email": "abigail@laravel.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:

```rust
app.post("/webhooks/stripe")
    .header("content-type", "application/json")
    .body(r#"{"type": "invoice.paid"}"#)
    .await
    .assert_ok();
```

<a name="uploading-files"></a>
### Uploading files

To test file uploads, pass an [`Attachment`](http-client.md#attaching-files) 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:

```rust
use laravel::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):

```rust
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.

<a name="cookies-and-sessions"></a>
### 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`:

```rust
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:

```rust
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:

```rust
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)`. Laravel handles cookie encryption automatically so your handler receives the value whether or not [`EncryptCookies`](cookies.md) 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`:

```rust
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");
```

<a name="acting-as-a-user"></a>
### Acting as a user

To send a request as a logged-in user, use `acting_as`:

```rust
use laravel::model::create;
use laravel::testing::prelude::*;

#[laravel::test]
async fn users_see_their_dashboard(app: Application) -> laravel::Result<()> {
    let user = create!(User {
        name: "Taylor",
        email: "taylor@laravel.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`:

```rust
app.post("/login")
    .form([("email", "taylor@laravel.com"), ("password", "password")])
    .await
    .assert_redirect_to("/dashboard")
    .assert_authenticated_as(&user);

app.post("/login")
    .form([("email", "taylor@laravel.com"), ("password", "wrong")])
    .await
    .assert_guest();
```

<a name="following-redirects"></a>
### Following redirects

To test the page that a form redirects to, call `follow_redirects`:

```rust
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`.

<a name="redirecting-back"></a>
### 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`:

```rust
use laravel::testing::prelude::*;

#[laravel::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.

<a name="available-assertions"></a>
## 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](#cookies-and-sessions), [authentication](#acting-as-a-user), [JSON](#testing-json-apis), [Inertia](#testing-inertia-pages), [views](#testing-views), [head metadata](#testing-head-metadata), and [errors](#testing-errors).

<a name="status-assertions"></a>
### Status assertions

Use `assert_status` with a status code number or `StatusCode`, or call one of the named helpers for common HTTP statuses:

```rust
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` 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` |

<a name="redirect-assertions"></a>
### Redirect assertions

Verify redirect responses and their target URLs or routes:

```rust
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@laravel.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]urls.md#signed-urls 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]#redirecting-back |

<a name="header-and-download-assertions"></a>
### Header and download assertions

Check response headers or verify that a response initiates a file download:

```rust
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 |

<a name="content-assertions"></a>
### Content assertions

Assert on the text or raw HTML rendered in a response body:

```rust
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) |

<a name="validation-assertions"></a>
### Validation assertions

Check which fields failed or passed validation. These assertions work for both JSON `422` responses and session-flashed web errors:

```rust
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]validation.md#pages-with-several-forms |

<a name="inspecting-responses-directly"></a>
### 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:

```rust
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`.

<a name="testing-json-apis"></a>
## 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:

```json
{
    "data": [
        { "id": 1, "name": "Taylor", "email": "taylor@laravel.com" },
        { "id": 2, "name": "Abigail", "email": "abigail@laravel.com" }
    ],
    "meta": { "total": 2 }
}
```

You only need to specify the keys you want to verify:

```rust
use laravel::testing::prelude::*;

#[laravel::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`:

```rust
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`:

```rust
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:

```rust
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:

```rust
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.

<a name="fluent-json-assertions"></a>
### 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()`:

```rust
use laravel::testing::prelude::*;

#[laravel::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:

```rust
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 |

<a name="testing-inertia-pages"></a>
## Testing Inertia pages

To test an [Inertia](inertia.md) page, call `assert_inertia`, then assert on the page's component and props:

```rust
app.get("/users/1")
    .await
    .assert_inertia()
    .component("Users/Show")
    .has("user")
    .equals("user.name", "Taylor")
    .missing("user.password");
```

For the full list of Inertia page assertions and partial reload testing, check out [testing pages](inertia.md#testing-pages) in the Inertia guide.

<a name="testing-views"></a>
## Testing views

A response that rendered a [view](views.md) records the view's name and the template data passed to it:

```rust
use laravel::model::create;
use laravel::testing::prelude::*;

#[laravel::test]
async fn the_user_list_shows_each_user(app: Application) -> laravel::Result<()> {
    create!(User { name: "Taylor", email: "taylor@laravel.com", password: "password" }).await?;

    app.get("/users")
        .await
        .assert_view_is("users.index")
        .assert_view_has("users.0.name", "Taylor");

    Ok(())
}
```

<a name="testing-head-metadata"></a>
## Testing head metadata

`assert_head` reads a response's [head metadata](head.md), whether it's an HTML page or an Inertia page:

```rust
app.get("/posts/1")
    .await
    .assert_head()
    .title("Hello World · Laravel")
    .meta("og:title", "Hello World · Laravel")
    .missing("robots");
```

For the full list of `<head>` assertions, check out [testing the head](head.md#testing-the-head) in the head metadata guide.

<a name="testing-errors"></a>
## Testing errors

A response rendered for an [error](errors.md) 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:

```rust
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](errors.md#failures-and-expected-outcomes) (either because it failed the request or because it was passed to [`laravel::report`](errors.md#reporting-and-carrying-on)). 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.

<a name="testing-the-database"></a>
## 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.

<a name="refreshing-the-database"></a>
### Refreshing the database

To give each test a clean database built from your [migrations](migrations.md), 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`:

```rust
use laravel::foundation::ApplicationBuilder;

pub fn configure() -> ApplicationBuilder {
    crate::configure()
        .for_testing(env!("CARGO_MANIFEST_DIR"))
        .with_env("DATABASE_URL", "postgres://postgres@127.0.0.1/laravel_test")
        .refresh_database()
}
```

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:

```shell
touch 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 TABLE` commits 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](migrations.md#squashing-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!`](models.md#creating-models) (as in [Acting as a user](#acting-as-a-user)) or with [model factories](factories.md).

<a name="seeding-the-database"></a>
### Seeding the database

If a test only needs one or two records, prefer [model factories](factories.md) over a seeder so each test clearly shows the data it relies on:

```rust
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](seeding.md). It runs in the test's transaction, so its rows disappear when the test ends:

```rust
use app::seeders;
use laravel::testing::prelude::*;

#[laravel::test]
async fn the_archive_lists_every_post(app: Application) -> laravel::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`:

```rust
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:

```rust
fn app_with_posts() -> Application {
    app::testing::configure().seed(app::seeders::posts).create()
}

#[laravel::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`](#refreshing-the-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.

<a name="database-assertions"></a>
### 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:

```rust
use laravel::testing::prelude::*;

#[laravel::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:

```rust
let import = Import::find_or_fail(import.id).await?;

assert_eq!(import.status, "failed");
assert!(import.failed_at.is_some());
```

<a name="fakes"></a>
## 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]broadcasting.md#testing (`broadcast::fake`)
- [Events]events.md#testing-events (`event::fake`)
- [Feature flags]feature-flags.md#testing (`feature::fake`)
- [File storage]filesystem.md#testing (`storage::fake`)
- [HTTP client]http-client.md#testing (`client::fake`)
- [Mail]mail.md#testing (`mail::fake`)
- [Notifications]notifications.md#testing (`notification::fake`)
- [Processes]processes.md#testing (`process::fake`)
- [Queues]queues.md#testing (`queue::fake`)
- [SMS]sms.md#testing (`sms::fake`)

<a name="swapping-services"></a>
## Swapping services

To test code that interacts with an external system, such as a payment gateway, swap the real [service](container.md) in the container for a fake. For example, suppose your checkout handler injects a `Stripe` service:

```rust
use app::services::Stripe;
use laravel::prelude::*;

pub async fn store(stripe: Inject<Stripe>) -> laravel::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:

```rust
// src/services/stripe.rs
use 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) -> laravel::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(&cents));
    }
}
```

In your test, `app.swap` replaces the service in the container and returns an `Arc<Stripe>` handle for assertions:

```rust
use app::services::Stripe;
use laravel::testing::prelude::*;

#[laravel::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](container.md#trait-contracts), 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:

```rust
use std::sync::{Arc, Mutex};

use app::services::geocoder::{Coordinates, Geocoder};
use async_trait::async_trait;
use laravel::testing::prelude::*;

#[derive(Default)]
struct FakeGeocoder {
    addresses: Mutex<Vec<String>>,
}

#[async_trait]
impl Geocoder for FakeGeocoder {
    async fn locate(&self, address: &str) -> laravel::Result<Coordinates> {
        self.addresses.lock().unwrap().push(address.to_owned());

        Ok(Coordinates { latitude: 41.8781, longitude: -87.6298 })
    }
}

#[laravel::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"]);
}
```

<a name="time-travel"></a>
## 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:

```rust
use laravel::testing::prelude::*;

#[laravel::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 a `ZonedDateTime` or a `Timestamp`.
- `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()`](time.md#the-current-time) rather than `ZonedDateTime::now()` or `SystemTime::now()` so tests can control it.

<a name="testing-without-requests"></a>
## 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](container.md) with `app.resolve::<T>()`, returning the same instance your handlers receive. For example, suppose your application registers a `Cart` service with a `count` method:

```rust
use laravel::testing::prelude::*;

#[laravel::test]
async fn the_cart_starts_empty(app: Application) {
    let cart = app.resolve::<Cart>().await;

    assert_eq!(cart.count(), 0);
}
```

<a name="testing-console-commands"></a>
## Testing console commands

Call `app.command(...)` to execute a [console command](console.md), capture its output, and assert on both the exit status and output streams:

```rust
use laravel::testing::prelude::*;

#[laravel::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](console.md#testing-commands) in the console guide.