Skip to content

Testing

Testing

Testing

Introduction

Laravel is built with testing in mind. You can send HTTP requests through your application's middleware, routing, and handlers without starting a server, then check the responses in a few lines of code:

1package feature_test
2 
3import (
4 "testing"
5 
6 "app/tests"
7)
8 
9func TestTheWelcomePageRenders(t *testing.T) {
10 client := tests.New(t)
11 
12 client.Get("/").AssertOK()
13}
1package feature_test
2 
3import (
4 "testing"
5 
6 "app/tests"
7)
8 
9func TestTheWelcomePageRenders(t *testing.T) {
10 client := tests.New(t)
11 
12 client.Get("/").AssertOK()
13}

In this test, tests.New builds your application and returns a client for it. Get sends a GET request through your middleware, routing, and error handling, as a request from a browser goes, and AssertOK checks for a 200 status code. Most of your tests should look like this one, because a test that sends a request checks your routes, middleware, and handlers together.

When a handler starts background work, the request returns once the work has finished, so the test may check what the work did.

Writing tests

Laravel tests are ordinary Go tests, so you run them with the tools you already use. A test is a function whose name starts with Test, in a file whose name ends in _test.go.

Your application's tests live in the tests/feature directory, in the feature_test package. New applications start with tests/feature/welcome_test.go, which checks the welcome page. Add a file beside it for each part of your application, such as posts_test.go for your posts. Each test builds your application with tests.New, which tests/tests.go defines:

1package tests
2 
3import (
4 "testing"
5 
6 "go.laravel.com/laraveltest"
7 
8 "app/bootstrap"
9)
10 
11func New(t testing.TB, with ...laraveltest.Option) *laraveltest.Client {
12 with = append([]laraveltest.Option{
13 laraveltest.Env(map[string]string{
14 "APP_ENV": "testing",
15 "APP_DEBUG": "true",
16 "BCRYPT_ROUNDS": "4",
17 "BROADCAST_CONNECTION": "discard",
18 "CACHE_STORE": "memory",
19 "FEATURE_STORE": "memory",
20 "INERTIA_SSR": "false",
21 "MAIL_MAILER": "log",
22 "OTEL_SDK_DISABLED": "true",
23 "QUEUE_CONNECTION": "sync",
24 "SESSION_DRIVER": "memory",
25 "SMS_SENDER": "log",
26 "WORKFLOW_STORE": "memory",
27 }),
28 laraveltest.RefreshDatabase,
29 }, with...)
30 
31 return laraveltest.New(t, bootstrap.Options(), with...)
32}
1package tests
2 
3import (
4 "testing"
5 
6 "go.laravel.com/laraveltest"
7 
8 "app/bootstrap"
9)
10 
11func New(t testing.TB, with ...laraveltest.Option) *laraveltest.Client {
12 with = append([]laraveltest.Option{
13 laraveltest.Env(map[string]string{
14 "APP_ENV": "testing",
15 "APP_DEBUG": "true",
16 "BCRYPT_ROUNDS": "4",
17 "BROADCAST_CONNECTION": "discard",
18 "CACHE_STORE": "memory",
19 "FEATURE_STORE": "memory",
20 "INERTIA_SSR": "false",
21 "MAIL_MAILER": "log",
22 "OTEL_SDK_DISABLED": "true",
23 "QUEUE_CONNECTION": "sync",
24 "SESSION_DRIVER": "memory",
25 "SMS_SENDER": "log",
26 "WORKFLOW_STORE": "memory",
27 }),
28 laraveltest.RefreshDatabase,
29 }, with...)
30 
31 return laraveltest.New(t, bootstrap.Options(), with...)
32}

laraveltest.New builds the application as main.go does, from bootstrap.Options, including your services. Each option in with changes the application for one test, such as laraveltest.FakeDisk("public"). Your application's tests.New adds RefreshDatabase, so every test gets a database of its own. Keep what every test needs in tests.New, so each test only names what it changes. Tests of your jobs, listeners, and commands use tests.New too, so they belong in tests/feature as well.

Code that only computes a value, such as a function that prices an order, doesn't need the application. Test it with a plain Go test beside the code, in the same package:

1package orders
2 
3import "testing"
4 
5func TestShippingIsFreeOverFiftyDollars(t *testing.T) {
6 if got := Shipping(Order{Subtotal: 6000}); got != 0 {
7 t.Errorf("shipping was %d, want 0", got)
8 }
9}
1package orders
2 
3import "testing"
4 
5func TestShippingIsFreeOverFiftyDollars(t *testing.T) {
6 if got := Shipping(Order{Subtotal: 6000}); got != 0 {
7 t.Errorf("shipping was %d, want 0", got)
8 }
9}

When an assertion fails, it reports the failure on the test, with what it expected and the response it got, and the test carries on. Each assertion returns the response, so you may chain them:

1client.Get("/").AssertOK().AssertSee("Laravel").AssertHeader("Content-Type", "text/html; charset=utf-8")
1client.Get("/").AssertOK().AssertSee("Laravel").AssertHeader("Content-Type", "text/html; charset=utf-8")

Each call to tests.New builds a new application that has its own services, clock, sessions, and configuration, so one test can't change what another sees, and tests may run in parallel with t.Parallel().

Running tests

Run your tests with Go's test runner. To run only some of them, name the package and pass a pattern that matches part of their names:

1go test ./...
2 
3go test ./tests/feature -run Invitations
1go test ./...
2 
3go test ./tests/feature -run Invitations

The application under test logs to the test, so a failing test shows each request it sent and each error the application reported. Pass -v to see the log of passing tests too. On your CI server, add -race to run your tests with Go's race detector, which finds handlers that share data without a lock.

Configuring your tests

laraveltest.New reads your .env file (with variables set in your shell taking precedence), sets APP_ENV to testing, and applies the overrides passed with laraveltest.Env in tests/tests.go. Any variable in .env that tests/tests.go doesn't override, 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, laraveltest.New fills in a fresh APP_KEY and the same fast, in-memory fallbacks that tests/tests.go sets so your tests still run.

To change a variable for every test, add or edit an entry in laraveltest.Env inside tests/tests.go. To let a .env value take effect instead of an override in tests/tests.go, such as testing against a Redis cache configured in .env, remove that entry from tests/tests.go.

You may also create a .env.testing file in your project root. When .env.testing exists, laraveltest.New reads it instead of .env, and the overrides in tests/tests.go still apply on top of it.

To override a variable for one test, pass laraveltest.Env to tests.New. Later laraveltest.Env options layer on top of earlier ones, and they configure both Laravel's settings and the settings your services and packages read. For example, this test checks a page with debug mode off, as production runs:

1func TestErrorsHideTheirDetailsInProduction(t *testing.T) {
2 client := tests.New(t, laraveltest.Env(map[string]string{
3 "APP_DEBUG": "false",
4 }))
5 
6 client.Get("/reports/broken").AssertStatus(500).AssertDontSee("connection refused")
7}
1func TestErrorsHideTheirDetailsInProduction(t *testing.T) {
2 client := tests.New(t, laraveltest.Env(map[string]string{
3 "APP_DEBUG": "false",
4 }))
5 
6 client.Get("/reports/broken").AssertStatus(500).AssertDontSee("connection refused")
7}

The same option sets variables your own services read from env in services.New:

1func TestPricesAreShownInEuros(t *testing.T) {
2 client := tests.New(t, laraveltest.Env(map[string]string{
3 "BILLING_CURRENCY": "eur",
4 }))
5 
6 client.Get("/pricing").AssertSee("€")
7}
1func TestPricesAreShownInEuros(t *testing.T) {
2 client := tests.New(t, laraveltest.Env(map[string]string{
3 "BILLING_CURRENCY": "eur",
4 }))
5 
6 client.Get("/pricing").AssertSee("€")
7}

Pass an empty string, such as "STRIPE_KEY": "", to clear a variable inherited from .env for a single test.

Making requests

The client has a method for each HTTP method. Each takes a path, which may include a query string, and returns a *webtest.Response for chaining assertions:

1func TestPostsAreListed(t *testing.T) {
2 client := tests.New(t)
3 
4 client.Get("/posts?page=2").AssertOK().AssertSee("Posts")
5}
1func TestPostsAreListed(t *testing.T) {
2 client := tests.New(t)
3 
4 client.Get("/posts?page=2").AssertOK().AssertSee("Posts")
5}

Post, Put, and Patch take the form to send, and Delete and Head take only the path. The client sends Sec-Fetch-Site: same-origin with each request, as a browser does for your own pages, so its requests pass CSRF protection without a token.

Named routes

To avoid hardcoding paths that your router already names, build URLs with client.Route, client.SignedRoute, and client.TemporarySignedRoute. Each fails the test if the route name or parameters are invalid:

1post := client.Create(factories.Post)
2 
3client.Get(client.Route("posts.show", "post", &post)).AssertOK()
4 
5link := client.TemporarySignedRoute("invitations.accept", time.Hour, "invitation", invitation.ID)
6client.Get(link).AssertOK()
1post := client.Create(factories.Post)
2 
3client.Get(client.Route("posts.show", "post", &post)).AssertOK()
4 
5link := client.TemporarySignedRoute("invitations.accept", time.Hour, "invitation", invitation.ID)
6client.Get(link).AssertOK()

Customizing request headers

WithHeader returns a client that sends a header with every request:

1client.WithHeader("Accept-Language", "fr").Get("/").AssertSee("Bienvenue")
1client.WithHeader("Accept-Language", "fr").Get("/").AssertSee("Bienvenue")

To authenticate an API request with a bearer token, call WithToken, which sets the Authorization header:

1client.WithToken("test-token").GetJSON("/api/user").AssertOK()
1client.WithToken("test-token").GetJSON("/api/user").AssertOK()

The client that WithHeader or WithToken returns shares its cookies with the client it came from, so you may add a header for a single request without losing the session.

Requests come from the address 192.0.2.1. To send them from another IP address, such as when you test trusted proxies or rate limits, use WithIP:

1client.WithIP("203.0.113.7").Post("/login", nil).AssertRedirect("/login")
1client.WithIP("203.0.113.7").Post("/login", nil).AssertRedirect("/login")

Sending input

Post, Put, and Patch send a form, as a browser submits one, so a form that fails validation redirects back with its errors. The form is a url.Values, the standard library's type for form fields, and nil sends no input. To send JSON to an API instead, use PostJSON, PutJSON, or PatchJSON, which Testing JSON APIs covers:

1func TestUsersCanSignUp(t *testing.T) {
2 client := tests.New(t)
3 
4 client.Post("/sign-up", url.Values{
5 "name": {"Taylor"},
6 "email": {"[email protected]"},
7 "password": {"secret123"},
8 "password_confirmation": {"secret123"},
9 }).AssertRedirect("/dashboard")
10 
11 client.PostJSON("/api/users", map[string]any{"name": "Abigail", "email": "[email protected]"}).
12 AssertCreated()
13}
1func TestUsersCanSignUp(t *testing.T) {
2 client := tests.New(t)
3 
4 client.Post("/sign-up", url.Values{
5 "name": {"Taylor"},
6 "email": {"[email protected]"},
7 "password": {"secret123"},
8 "password_confirmation": {"secret123"},
9 }).AssertRedirect("/dashboard")
10 
11 client.PostJSON("/api/users", map[string]any{"name": "Abigail", "email": "[email protected]"}).
12 AssertCreated()
13}

To send a raw body exactly as you wrote it, such as a signed webhook payload, use PostBody, PutBody, or PatchBody with the content type and bytes:

1client.WithHeader("Stripe-Signature", signature).
2 PostBody("/webhooks/stripe", "application/json", []byte(`{"type": "invoice.paid"}`)).
3 AssertOK()
1client.WithHeader("Stripe-Signature", signature).
2 PostBody("/webhooks/stripe", "application/json", []byte(`{"type": "invoice.paid"}`)).
3 AssertOK()

For any other HTTP method or custom request setup, build an *http.Request with httptest.NewRequest and send it with Do:

1request := httptest.NewRequest("POST", "/webhooks/stripe", strings.NewReader(`{"type": "invoice.paid"}`))
2request.Header.Set("Content-Type", "application/json")
3 
4client.Do(request).AssertOK()
1request := httptest.NewRequest("POST", "/webhooks/stripe", strings.NewReader(`{"type": "invoice.paid"}`))
2request.Header.Set("Content-Type", "application/json")
3 
4client.Do(request).AssertOK()

Uploading files

To test a file upload, call Upload, which sends a multipart form in a POST request with the fields and files you give it. A webtest.File names the form field, the file, and the file's content, which you may read from a fixture in your testdata directory:

1png, err := os.ReadFile("testdata/avatar.png")
2if err != nil {
3 t.Fatal(err)
4}
5 
6client.Upload("/profile/avatar", url.Values{"caption": {"Me"}}, webtest.File{
7 Field: "avatar",
8 Name: "avatar.png",
9 Content: png,
10}).AssertRedirect("/profile")
1png, err := os.ReadFile("testdata/avatar.png")
2if err != nil {
3 t.Fatal(err)
4}
5 
6client.Upload("/profile/avatar", url.Values{"caption": {"Me"}}, webtest.File{
7 Field: "avatar",
8 Name: "avatar.png",
9 Content: png,
10}).AssertRedirect("/profile")

To test a size limit or an image upload without keeping a fixture file in your repository, use webtest.FakeFile(field, name, kilobytes), which makes a file of that size, or webtest.FakeImage(field, name, width, height), which makes a valid PNG of those dimensions:

1client.Upload("/profile/avatar", nil, webtest.FakeImage("avatar", "avatar.png", 640, 480)).
2 AssertRedirect("/profile")
3 
4client.Upload("/documents", nil, webtest.FakeFile("document", "report.pdf", 6000)).
5 AssertInvalid("document")
1client.Upload("/profile/avatar", nil, webtest.FakeImage("avatar", "avatar.png", 640, 480)).
2 AssertRedirect("/profile")
3 
4client.Upload("/documents", nil, webtest.FakeFile("document", "report.pdf", 6000)).
5 AssertInvalid("document")

Because FakeFile fills the file with zeros, validation rules that check what a file contains, such as rule.Image and rule.Mimes, reject it.

Cookies and sessions

The client keeps the cookies it receives and sends them with its later requests, as a browser does. So one test can follow a visitor across several requests, and the session carries over from each request to the next:

1func TestTheCartRemembersItsItems(t *testing.T) {
2 client := tests.New(t)
3 
4 client.Post("/cart", url.Values{"product": {"42"}}).AssertRedirect("/cart")
5 
6 client.Get("/cart").AssertOK().AssertSee("1 item")
7}
1func TestTheCartRemembersItsItems(t *testing.T) {
2 client := tests.New(t)
3 
4 client.Post("/cart", url.Values{"product": {"42"}}).AssertRedirect("/cart")
5 
6 client.Get("/cart").AssertOK().AssertSee("1 item")
7}

Every test starts with no session. To start one with data already in it, such as a coupon that an earlier page stored, call WithSession. Then use AssertSessionHas and AssertSessionMissing to check what the handler stored or flashed:

1client.WithSession(map[string]any{"coupon": "WELCOME10"}).
2 Post("/checkout", nil).
3 AssertRedirect("/orders").
4 AssertSessionHas("status", "Order placed!").
5 AssertSessionMissing("coupon")
1client.WithSession(map[string]any{"coupon": "WELCOME10"}).
2 Post("/checkout", nil).
3 AssertRedirect("/orders").
4 AssertSessionHas("status", "Order placed!").
5 AssertSessionMissing("coupon")

Session keys may use dot notation, such as settings.theme. Use AssertSessionPresent to check only that a key has a value, or AssertSessionWhere to check the value with a function of your own, whose argument type is the type to read the value as:

1client.Post("/cart", url.Values{"product": {"7"}}).
2 AssertSessionPresent("cart").
3 AssertSessionWhere("cart", func(cart []int) bool { return slices.Contains(cart, 7) })
1client.Post("/cart", url.Values{"product": {"7"}}).
2 AssertSessionPresent("cart").
3 AssertSessionWhere("cart", func(cart []int) bool { return slices.Contains(cart, 7) })

The session assertions work only on routes that run the session middleware, such as the routes in routes/web.go.

To send a cookie of your own, call WithCookie with its plain value, even when the route encrypts its cookies. On the response, AssertCookie checks a cookie's value as your application set it, before encryption, and AssertCookieExpired checks that the response removes a cookie. AssertCookiePresent and AssertCookieMissing check whether the response sets a cookie at all:

1client.WithCookie("theme", "dark").Get("/").AssertSee("dark")
2 
3client.Post("/theme", url.Values{"theme": {"dark"}}).AssertCookie("theme", "dark")
4 
5client.Post("/tour/dismiss", nil).AssertCookieExpired("tour")
1client.WithCookie("theme", "dark").Get("/").AssertSee("dark")
2 
3client.Post("/theme", url.Values{"theme": {"dark"}}).AssertCookie("theme", "dark")
4 
5client.Post("/tour/dismiss", nil).AssertCookieExpired("tour")

A client acts as one browser. Every client you make from it with WithHeader, WithCookie, From, or ActingAs shares its cookies, and so shares its session. To follow a second visitor, or the same user on a second device, call NewBrowser. It returns a client of the same application, with the same database, clock, and fakes, but with a cookie jar of its own. For example, this test checks that changing a password logs the user out on their other devices:

1func TestChangingThePasswordLogsOutOtherDevices(t *testing.T) {
2 client := tests.New(t)
3 client.Create(factories.User, func(u *models.User) { u.Email = "[email protected]" })
4 login := url.Values{"email": {"[email protected]"}, "password": {"password"}}
5 
6 laptop := client
7 laptop.Post("/login", login).AssertAuthenticated()
8 phone := client.NewBrowser()
9 phone.Post("/login", login).AssertAuthenticated()
10 
11 laptop.Put("/settings/password", url.Values{
12 "current_password": {"password"},
13 "password": {"new-password"},
14 "password_confirmation": {"new-password"},
15 }).AssertValid()
16 
17 laptop.Get("/dashboard").AssertOK()
18 phone.Get("/dashboard").AssertRedirect("/login")
19}
1func TestChangingThePasswordLogsOutOtherDevices(t *testing.T) {
2 client := tests.New(t)
3 client.Create(factories.User, func(u *models.User) { u.Email = "[email protected]" })
4 login := url.Values{"email": {"[email protected]"}, "password": {"password"}}
5 
6 laptop := client
7 laptop.Post("/login", login).AssertAuthenticated()
8 phone := client.NewBrowser()
9 phone.Post("/login", login).AssertAuthenticated()
10 
11 laptop.Put("/settings/password", url.Values{
12 "current_password": {"password"},
13 "password": {"new-password"},
14 "password_confirmation": {"new-password"},
15 }).AssertValid()
16 
17 laptop.Get("/dashboard").AssertOK()
18 phone.Get("/dashboard").AssertRedirect("/login")
19}

Calling tests.New a second time doesn't give you a second browser. It builds a separate application that has its own encryption key, database transaction, and clock.

Acting as a user

Most pages of an application are for logged-in users, such as a dashboard. To send a request as a user, create one with a factory and pass it to ActingAs, which returns a client whose requests are that user's:

1package feature_test
2 
3import (
4 "testing"
5 
6 "app/database/factories"
7 "app/tests"
8)
9 
10func TestUsersSeeTheirDashboard(t *testing.T) {
11 client := tests.New(t)
12 user := client.Create(factories.User)
13 
14 client.ActingAs(&user).Get("/dashboard").AssertOK()
15}
1package feature_test
2 
3import (
4 "testing"
5 
6 "app/database/factories"
7 "app/tests"
8)
9 
10func TestUsersSeeTheirDashboard(t *testing.T) {
11 client := tests.New(t)
12 user := client.Create(factories.User)
13 
14 client.ActingAs(&user).Get("/dashboard").AssertOK()
15}

To check who is logged in after a login, registration, or logout request, use AssertAuthenticated, AssertAuthenticatedAs(&user), or AssertGuest. They read the session that the request left, so a request sent with ActingAs counts as a guest's unless your handler logs the user in. A user from your factory has the password password:

1client.Post("/login", url.Values{"email": {user.Email}, "password": {"password"}}).
2 AssertRedirect("/dashboard").
3 AssertAuthenticatedAs(&user)
4 
5client.NewBrowser().Post("/login", url.Values{"email": {user.Email}, "password": {"wrong"}}).
6 AssertGuest()
1client.Post("/login", url.Values{"email": {user.Email}, "password": {"password"}}).
2 AssertRedirect("/dashboard").
3 AssertAuthenticatedAs(&user)
4 
5client.NewBrowser().Post("/login", url.Values{"email": {user.Email}, "password": {"wrong"}}).
6 AssertGuest()

To learn more, check out the authentication guide's section on testing.

Following redirects

A form usually answers with a redirect, and the visitor sees the page the redirect leads to. The client follows each redirect as a browser does: it sends a GET request with the cookies it received, so one request checks both steps. AssertRedirect checks where the request you sent redirected, and the assertions after it check the page the visitor lands on, including its flash message:

1client.Post("/posts", url.Values{"title": {"Hello"}}).
2 AssertRedirect("/posts").
3 AssertOK().
4 AssertSee("Post created!")
1client.Post("/posts", url.Values{"title": {"Hello"}}).
2 AssertRedirect("/posts").
3 AssertOK().
4 AssertSee("Post created!")

The validation and session assertions read the session as the request you sent left it, before the client followed its redirect, so they still see the errors and data it flashed.

The client stops at a redirect to another site, such as a payment provider's checkout, and returns that redirect for you to check with AssertRedirect. To check a redirect's own status or headers, send the request with WithoutRedirects:

1client.WithoutRedirects().Post("/posts", url.Values{"title": {"Hello"}}).
2 AssertFound().
3 AssertHeader("Location", "/posts")
1client.WithoutRedirects().Post("/posts", url.Values{"title": {"Hello"}}).
2 AssertFound().
3 AssertHeader("Location", "/posts")

Redirecting back

A form that fails validation sends the browser back to the page it came from and flashes the errors and the input it sent. Tell the test client which page the request came from with From, then check the redirect with AssertRedirectBackWithErrors:

1func TestSignUpsNeedAValidEmail(t *testing.T) {
2 client := tests.New(t)
3 
4 form := url.Values{"name": {"Taylor"}, "email": {"taylor"}, "password": {"secret123"}}
5 
6 client.From("/sign-up").Post("/sign-up", form).
7 AssertRedirectBackWithErrors("email").
8 AssertSessionHasInput("email", "taylor").
9 AssertSessionMissingInput("password")
10}
1func TestSignUpsNeedAValidEmail(t *testing.T) {
2 client := tests.New(t)
3 
4 form := url.Values{"name": {"Taylor"}, "email": {"taylor"}, "password": {"secret123"}}
5 
6 client.From("/sign-up").Post("/sign-up", form).
7 AssertRedirectBackWithErrors("email").
8 AssertSessionHasInput("email", "taylor").
9 AssertSessionMissingInput("password")
10}

From sets the request's Referer header. AssertRedirectBack checks only the redirect, and AssertRedirectBackWithoutErrors also checks that validation passed. AssertSessionHasInput checks the old input that the next page's form shows, and password fields are never flashed.

Available assertions

Every assertion on a response returns the response, so you can chain several checks together. Besides the assertions below, dedicated sections cover cookies and sessions, authentication, JSON, Inertia, views, head metadata, and errors.

Status assertions

Use AssertStatus with a status code, or call one of the named assertions for common HTTP statuses:

1client.Get("/posts").AssertOK()
2client.PostJSON("/api/posts", map[string]any{"title": "Hello"}).AssertCreated()
3client.Delete("/api/posts/1").AssertNoContent()
4client.Get("/missing").AssertNotFound()
5client.Get("/custom").AssertStatus(http.StatusTeapot)
1client.Get("/posts").AssertOK()
2client.PostJSON("/api/posts", map[string]any{"title": "Hello"}).AssertCreated()
3client.Delete("/api/posts/1").AssertNoContent()
4client.Get("/missing").AssertNotFound()
5client.Get("/custom").AssertStatus(http.StatusTeapot)
Assertion Asserts
AssertStatus(status) The exact status code
AssertOK(), AssertCreated(), AssertAccepted(), AssertNoContent() A 200, 201, 202, or 204 with an empty body
AssertSuccessful(), AssertClientError(), AssertServerError() Any 2xx, 4xx, or 5xx status
AssertBadRequest(), AssertUnauthorized(), AssertPaymentRequired(), AssertForbidden(), AssertNotFound() A 400, 401, 402, 403, or 404
AssertMethodNotAllowed(), AssertNotAcceptable(), AssertRequestTimeout(), AssertConflict(), AssertGone() A 405, 406, 408, 409, or 410
AssertUnsupportedMediaType(), AssertUnprocessable(), AssertFailedDependency(), AssertTooManyRequests() A 415, 422, 424, or 429
AssertInternalServerError(), AssertServiceUnavailable() A 500 or 503

Redirect assertions

To check where a request redirected, pass the path or URL to AssertRedirect. To check that it redirected to a named route, use AssertRedirectToRoute with the route's name and parameters, as urls.Route takes them. AssertRedirectToSignedRoute also checks that the URL has a valid signature that hasn't expired:

1client.Post("/posts", url.Values{"title": {"Hello"}}).AssertRedirect("/posts")
2 
3client.Post("/orders", url.Values{"plan": {"pro"}}).AssertRedirectToRoute("orders.show", "order", 1)
4 
5client.Post("/invitations", url.Values{"email": {"[email protected]"}}).
6 AssertRedirectToSignedRoute("invitations.accept", "invitation", 7)
1client.Post("/posts", url.Values{"title": {"Hello"}}).AssertRedirect("/posts")
2 
3client.Post("/orders", url.Values{"plan": {"pro"}}).AssertRedirectToRoute("orders.show", "order", 1)
4 
5client.Post("/invitations", url.Values{"email": {"[email protected]"}}).
6 AssertRedirectToSignedRoute("invitations.accept", "invitation", 7)
Assertion Asserts
AssertRedirect(location), AssertRedirectContains(text) That the request you sent redirected to the path or URL, or to a location that contains the text
AssertRedirectToRoute(name, params...) A redirect to the named route
AssertRedirectToSignedRoute(name, params...) A redirect to a valid signed URL of the named route
AssertRedirectBack(), AssertRedirectBackWithErrors(fields...), AssertRedirectBackWithoutErrors() A redirect back to the page the request came from
AssertMovedPermanently(), AssertFound(), AssertNotModified(), AssertTemporaryRedirect(), AssertPermanentRedirect() A 301, 302, 304, 307, or 308, which you see only without following redirects

Header and download assertions

To check a response's headers, or that a response downloads a file, use the header and download assertions:

1client.Get("/api/posts").
2 AssertHeader("X-Request-Id", "req_123").
3 AssertHeaderContains("Cache-Control", "no-store").
4 AssertHeaderPresent("ETag").
5 AssertHeaderMissing("X-Powered-By")
6 
7client.Get("/invoices/1/download").AssertOK().AssertDownload("invoice-1.pdf")
1client.Get("/api/posts").
2 AssertHeader("X-Request-Id", "req_123").
3 AssertHeaderContains("Cache-Control", "no-store").
4 AssertHeaderPresent("ETag").
5 AssertHeaderMissing("X-Powered-By")
6 
7client.Get("/invoices/1/download").AssertOK().AssertDownload("invoice-1.pdf")
Assertion Asserts
AssertHeader(key, value), AssertHeaderContains(key, text) A header's exact value, or part of it
AssertHeaderPresent(key), AssertHeaderMissing(key) That the response has the header, or doesn't
AssertDownload(name) That the response downloads a file with the name

Content assertions

To check the text or HTML in a response's body, use the content assertions:

1client.Get("/posts").
2 AssertOK().
3 AssertSee("Taylor's Post").
4 AssertDontSee("Draft Post").
5 AssertSeeInOrder("First Post", "Second Post").
6 AssertSeeHTML("<h1>Posts</h1>")
1client.Get("/posts").
2 AssertOK().
3 AssertSee("Taylor's Post").
4 AssertDontSee("Draft Post").
5 AssertSeeInOrder("First Post", "Second Post").
6 AssertSeeHTML("<h1>Posts</h1>")
Assertion Asserts
AssertSee(text), AssertDontSee(text) That the body contains the text, or doesn't, as written or as a template escapes it
AssertSeeInOrder(texts...) That the body contains the texts in order
AssertSeeHTML(markup), AssertDontSeeHTML(markup) That the body contains the markup exactly as written, or doesn't

Validation assertions

To check which fields failed or passed validation, use the validation assertions. They read the errors from a 422 JSON response, or from the session when a form was sent back:

1client.Post("/sign-up", url.Values{"name": {"Taylor"}, "email": {"not-an-email"}}).
2 AssertInvalid("email", "password").
3 AssertValid("name").
4 AssertInvalidMessage("email", "valid email")
5 
6client.Post("/settings/password", url.Values{"password": {"short"}}).
7 AssertInvalidIn("password", "password")
1client.Post("/sign-up", url.Values{"name": {"Taylor"}, "email": {"not-an-email"}}).
2 AssertInvalid("email", "password").
3 AssertValid("name").
4 AssertInvalidMessage("email", "valid email")
5 
6client.Post("/settings/password", url.Values{"password": {"short"}}).
7 AssertInvalidIn("password", "password")
Assertion Asserts
AssertInvalid(fields...) That validation failed with an error for each field
AssertValid(fields...) That none of the fields has an error, or with no fields, that validation passed
AssertInvalidMessage(field, text) That one of the field's error messages contains the text
AssertInvalidIn(bag, fields...), AssertInvalidMessageIn(bag, field, text), AssertValidIn(bag, fields...) The same checks, for a form that puts its errors in a named bag

Inspecting responses directly

For a check that no assertion covers, read the response's Status, Header, and Body fields, and report with t.Errorf, as in any Go test. Cookie(name) returns a cookie that the response set, holding its decrypted value, and JSON[T]() decodes the body into a value of type T. The Request field holds the request as your application saw it, such as which route answered:

1res := client.Get("/users/7").AssertOK()
2 
3if name := res.Request.Route().Name; name != "users.show" {
4 t.Errorf("the route was %q", name)
5}
6 
7t.Log(res.Body)
1res := client.Get("/users/7").AssertOK()
2 
3if name := res.Request.Route().Name; name != "users.show" {
4 t.Errorf("the route was %q", name)
5}
6 
7t.Log(res.Body)

Go shows what a test logs only when the test fails, or when you pass -v to go test.

Testing JSON APIs

GetJSON sends a GET request that asks for JSON back. PostJSON, PutJSON, and PatchJSON do the same and send a value of yours as the JSON body, such as a struct or a map. DeleteJSON sends a DELETE request that asks for JSON back, with an optional JSON body.

AssertJSON checks that the body contains a value. Mirror the structure down to the fields you care about, and Laravel ignores the keys of an object that you don't mention, such as id, email, or meta, and the items of a list after the ones you give. A list's items are compared in order, starting from the first. For example, if /api/users returns:

1{
2 "data": [
3 { "id": 1, "name": "Taylor", "email": "[email protected]" },
4 { "id": 2, "name": "Abigail", "email": "[email protected]" }
5 ],
6 "meta": { "total": 2 }
7}
1{
2 "data": [
3 { "id": 1, "name": "Taylor", "email": "[email protected]" },
4 { "id": 2, "name": "Abigail", "email": "[email protected]" }
5 ],
6 "meta": { "total": 2 }
7}

You only need to give the keys you want to check:

1func TestUsersAreListed(t *testing.T) {
2 client := tests.New(t)
3 
4 client.GetJSON("/api/users").AssertOK().AssertJSON(map[string]any{
5 "data": []any{
6 map[string]any{"name": "Taylor"},
7 map[string]any{"name": "Abigail"},
8 },
9 })
10}
1func TestUsersAreListed(t *testing.T) {
2 client := tests.New(t)
3 
4 client.GetJSON("/api/users").AssertOK().AssertJSON(map[string]any{
5 "data": []any{
6 map[string]any{"name": "Taylor"},
7 map[string]any{"name": "Abigail"},
8 },
9 })
10}

When the assertion fails, the failure names where the JSON first differs, such as data.1.name.

To check one value by its dot path, call AssertJSONPath. A path's segments are object keys and list indexes, so data.0.name reads the first user's name. To count the items of a list or object, use AssertJSONCount, where the path "" counts the body itself:

1client.GetJSON("/api/users").
2 AssertJSONPath("data.0.name", "Taylor").
3 AssertJSONCount("data", 2)
1client.GetJSON("/api/users").
2 AssertJSONPath("data.0.name", "Taylor").
3 AssertJSONCount("data", 2)

To check a value with your own code, pass a function to AssertJSONPathWhere, whose argument type is the type to read the value as. To check that a path has no value, use AssertJSONMissingPath:

1client.GetJSON("/api/users").
2 AssertJSONPathWhere("meta.total", func(total int) bool { return total >= 2 }).
3 AssertJSONMissingPath("data.0.password")
1client.GetJSON("/api/users").
2 AssertJSONPathWhere("meta.total", func(total int) bool { return total >= 2 }).
3 AssertJSONMissingPath("data.0.password")

To match the whole body, with no other keys or items, use AssertExactJSON, or AssertSimilarJSON to accept lists in any order.

Whereas AssertJSON matches from the top of the body, AssertJSONFragment checks that an object appears anywhere in it, such as one user in a list, and AssertJSONMissing checks that it appears nowhere:

1client.GetJSON("/api/users").
2 AssertJSONFragment(map[string]any{"name": "Taylor", "role": "admin"}).
3 AssertJSONMissing(map[string]any{"name": "Jess"})
1client.GetJSON("/api/users").
2 AssertJSONFragment(map[string]any{"name": "Taylor", "role": "admin"}).
3 AssertJSONMissing(map[string]any{"name": "Jess"})

To check the keys and nesting of a body without pinning down its values, use AssertJSONStructure. A list names required keys, a map gives the structure of each key's value, and the key * gives the structure of every item in a list:

1client.GetJSON("/api/users").AssertJSONStructure(map[string]any{
2 "data": map[string]any{"*": []any{"id", "name", map[string]any{"team": []any{"id", "name"}}}},
3 "meta": []any{"total"},
4})
1client.GetJSON("/api/users").AssertJSONStructure(map[string]any{
2 "data": map[string]any{"*": []any{"id", "name", map[string]any{"team": []any{"id", "name"}}}},
3 "meta": []any{"total"},
4})

Use AssertExactJSONStructure if a key that the structure doesn't name should also fail the test.

To work with the body as your own type, decode it with JSON[T](), which fails the test when the body isn't valid JSON for that type. A field matches only the key with exactly its name, so give each field a json tag:

1type usersResponse struct {
2 Data []struct {
3 Name string `json:"name"`
4 } `json:"data"`
5}
6 
7body := client.GetJSON("/api/users").AssertOK().JSON[usersResponse]()
1type usersResponse struct {
2 Data []struct {
3 Name string `json:"name"`
4 } `json:"data"`
5}
6 
7body := client.GetJSON("/api/users").AssertOK().JSON[usersResponse]()

Fluent JSON assertions

An API response can start sending a field nobody meant to send, such as a sensitive column added to a model. AssertJSONMatches passes the body to a function of yours as a *webtest.JSON, and fails if any key in the body is left unchecked, unless you allow the rest with Etc:

1package feature_test
2 
3import (
4 "testing"
5 
6 "go.laravel.com/webtest"
7 
8 "app/tests"
9)
10 
11func TestUsersAreShownWithoutTheirPassword(t *testing.T) {
12 client := tests.New(t)
13 
14 client.GetJSON("/api/users/1").AssertJSONMatches(func(j *webtest.JSON) {
15 j.Equals("id", 1).
16 Equals("name", "Taylor").
17 Missing("password").
18 Scope("team", func(team *webtest.JSON) { team.Has("id").Etc() })
19 })
20}
1package feature_test
2 
3import (
4 "testing"
5 
6 "go.laravel.com/webtest"
7 
8 "app/tests"
9)
10 
11func TestUsersAreShownWithoutTheirPassword(t *testing.T) {
12 client := tests.New(t)
13 
14 client.GetJSON("/api/users/1").AssertJSONMatches(func(j *webtest.JSON) {
15 j.Equals("id", 1).
16 Equals("name", "Taylor").
17 Missing("password").
18 Scope("team", func(team *webtest.JSON) { team.Has("id").Etc() })
19 })
20}

Use Scope to check the object or list at a path, with paths inside the function that start there, First to check a list's first item, Each to check every item, and Etc to allow the keys you don't check:

1client.GetJSON("/api/users").AssertJSONMatches(func(j *webtest.JSON) {
2 j.Count("data", 2).
3 First("data", func(user *webtest.JSON) { user.Equals("name", "Taylor").Etc() }).
4 Each("data", func(user *webtest.JSON) {
5 user.Where("id", func(id int) bool { return id > 0 }).Missing("password").Etc()
6 }).
7 Etc()
8})
1client.GetJSON("/api/users").AssertJSONMatches(func(j *webtest.JSON) {
2 j.Count("data", 2).
3 First("data", func(user *webtest.JSON) { user.Equals("name", "Taylor").Etc() }).
4 Each("data", func(user *webtest.JSON) {
5 user.Where("id", func(id int) bool { return id > 0 }).Missing("password").Etc()
6 }).
7 Etc()
8})
Method Asserts
Has(path), HasAny(paths...), Missing(path) That a path has a value, that one of the paths does, or that it has none
Equals(path, want) The value at a path
Where(path, check) That the value at a path passes your check, read as the function's argument type
Contains(path, item) That a list or object has the item
Count(path, n), CountBetween(path, least, most) How many items a list or object has
Scope(path, check), First(path, check), Each(path, check) The value at a path, a list's first item, or each item, with a function of its own
Etc() Nothing: it allows the keys the function doesn't check

Testing Inertia pages

To test an Inertia page, call AssertInertia with the page's component, then check its props by their dot paths with AssertProp and AssertPropMissing:

1client.Get("/users/1").
2 AssertOK().
3 AssertInertia("Users/Show").
4 AssertProp("user.name", "Taylor").
5 AssertPropMissing("user.password")
1client.Get("/users/1").
2 AssertOK().
3 AssertInertia("Users/Show").
4 AssertProp("user.name", "Taylor").
5 AssertPropMissing("user.password")

For deferred props, flash data, partial reloads, and checking every prop with AssertInertiaMatches, check out the Inertia guide's section on testing pages.

Testing views

A response that rendered a view keeps the view's name and the data your handler passed it, so you may check them without matching the HTML. AssertViewIs checks the name, and AssertViewHas checks a value at a dot path across map keys, exported struct fields, zero-argument exported methods (such as a paginator's Items), and slice indexes, such as Users.0.Name or Posts.Items.0.Title:

1func TestTheUserListShowsEachUser(t *testing.T) {
2 client := tests.New(t)
3 client.Create(factories.User, func(u *models.User) { u.Name = "Taylor" })
4 
5 client.Get("/users").
6 AssertOK().
7 AssertViewIs("users.index").
8 AssertViewHas("Users.0.Name", "Taylor")
9}
1func TestTheUserListShowsEachUser(t *testing.T) {
2 client := tests.New(t)
3 client.Create(factories.User, func(u *models.User) { u.Name = "Taylor" })
4 
5 client.Get("/users").
6 AssertOK().
7 AssertViewIs("users.index").
8 AssertViewHas("Users.0.Name", "Taylor")
9}

To compare the whole page with a view rendered from the data you expect, use AssertRenders, which the views guide's section on testing views describes.

Testing head metadata

To check a page's head metadata, such as its title and social tags, use AssertTitle, AssertMeta, and AssertMetaMissing. They read the <head> of an HTML page or the head prop of an Inertia page, so one test works for both:

1client.Get("/posts/1").
2 AssertOK().
3 AssertTitle("Hello World · Laravel").
4 AssertMeta("og:title", "Hello World · Laravel").
5 AssertMetaMissing("robots")
1client.Get("/posts/1").
2 AssertOK().
3 AssertTitle("Hello World · Laravel").
4 AssertMeta("og:title", "Hello World · Laravel").
5 AssertMetaMissing("robots")

For structured data, links such as a canonical URL, and the rest of the head assertions, check out the head guide's section on testing the head.

Testing errors

A response rendered for an error keeps the error it came from, so you can check the error itself instead of matching the page's text. For example, say your checkout handler fails with store.ErrCardDeclined when a card is declined. AssertError checks the response's error as errors.Is does, and AssertErrorWhere finds an error of a type, as errors.As does, and checks its fields:

1client.Post("/checkout", nil).AssertPaymentRequired().AssertError(store.ErrCardDeclined)
2 
3client.Post("/checkout", nil).AssertErrorWhere(func(err *store.DeclinedError) bool {
4 return err.Reason == "insufficient funds"
5})
1client.Post("/checkout", nil).AssertPaymentRequired().AssertError(store.ErrCardDeclined)
2 
3client.Post("/checkout", nil).AssertErrorWhere(func(err *store.DeclinedError) bool {
4 return err.Reason == "insufficient funds"
5})

AssertReported checks that the request reported a matching error, either because the request failed with it or because your code passed it to r.Report. AssertNotReported checks that the request reported no matching error, and AssertNothingReported checks that it reported no errors at all.

When laravel.Report reports an error outside a request, such as from a job, no response holds that error. Call AssertReported on the client instead, which checks every error the application reported during the test. To learn more, check out the error handling guide's section on testing errors.

Testing the database

A test that signs a user up or places an order needs a database with your tables in it, and with no rows left over from the tests before it. Laravel gives each test a database that your migrations built, and rolls back what the test wrote when the test ends.

Refreshing the database

Your application's tests.New passes laraveltest.RefreshDatabase to laraveltest.New, so every test it builds has a database:

1package feature_test
2 
3import (
4 "net/url"
5 "testing"
6 
7 "go.laravel.com/db"
8 
9 "app/tests"
10)
11 
12func TestPublishingAPostSavesIt(t *testing.T) {
13 client := tests.New(t)
14 
15 client.Post("/posts", url.Values{"title": {"Hello"}}).AssertRedirect("/posts")
16 
17 client.AssertDatabaseHas("posts", db.Values{"title": "Hello"})
18}
1package feature_test
2 
3import (
4 "net/url"
5 "testing"
6 
7 "go.laravel.com/db"
8 
9 "app/tests"
10)
11 
12func TestPublishingAPostSavesIt(t *testing.T) {
13 client := tests.New(t)
14 
15 client.Post("/posts", url.Values{"title": {"Hello"}}).AssertRedirect("/posts")
16 
17 client.AssertDatabaseHas("posts", db.Values{"title": "Hello"})
18}

Tests don't run against the database that DATABASE_URL names, because they would change your development data. Instead, each test package borrows a numbered copy of a test database beside it, which no other running package uses, so go test ./... can run your packages at once. For example, when DATABASE_URL is postgres://[email protected]/laravel, tests use laravel_test_1, laravel_test_2, and so on. RefreshDatabase uses DATABASE_URL from your .env or .env.testing file, your shell's environment, or laraveltest.Env. It creates the copies on PostgreSQL and MySQL, so the database user needs permission to create databases. On SQLite, each client gets a new database in memory instead.

The copies stay between test runs, so your tests don't wait for the migrations every time. When your application's code or the package's tests change, including a migration, Laravel rebuilds the package's copy from all of your migrations. If you've squashed your migrations into a schema file, Laravel loads that file first and then runs only the migrations you've added since, which builds a test database much faster when you have hundreds of migrations. Changing the schema file rebuilds the copy too.

If your application has no database, remove laraveltest.RefreshDatabase from tests/tests.go, and your tests won't need a database server.

Each client runs in a transaction that's never committed, so its changes disappear when the test ends. The client's requests, its factories, and the code you call with client.Context() all use that transaction, and your application's own transactions run as savepoints inside it. 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 connections, such as a queue worker you started yourself.

To give a test the rows it needs, create them with the client's Create and a model factory, as in Acting as a user. Create inserts the model through the client's transaction and fails the test when the insert fails.

Seeding the database

If a test only needs one or two records, prefer model factories over a seeder, so each test shows the data it relies on:

1user := client.Create(factories.User)
2 
3posts := client.CreateMany(3, factories.Post.For("user", user))
1user := client.Create(factories.User)
2 
3posts := client.CreateMany(3, factories.Post.For("user", user))

When a test needs a larger set of rows, call the client's Seed with the name of one of your seeders. It runs in the client's transaction, so its rows disappear when the test ends. With no names, it runs every seeder, as db:seed does:

1func TestTheArchiveListsEveryPost(t *testing.T) {
2 client := tests.New(t)
3 
4 client.Seed("posts").Get("/archive").AssertOK().AssertSee("Archive")
5}
1func TestTheArchiveListsEveryPost(t *testing.T) {
2 client := tests.New(t)
3 
4 client.Seed("posts").Get("/archive").AssertOK().AssertSee("Archive")
5}

When most of your tests need the same rows, such as your roles, seed each copy of the test database once instead. Add laraveltest.SeedOnce beside RefreshDatabase in tests/tests.go:

1func New(t testing.TB, with ...laraveltest.Option) *laraveltest.Client {
2 with = append([]laraveltest.Option{
3 laraveltest.RefreshDatabase,
4 laraveltest.SeedOnce("roles"),
5 }, with...)
6 
7 return laraveltest.New(t, bootstrap.Options(), with...)
8}
1func New(t testing.TB, with ...laraveltest.Option) *laraveltest.Client {
2 with = append([]laraveltest.Option{
3 laraveltest.RefreshDatabase,
4 laraveltest.SeedOnce("roles"),
5 }, with...)
6 
7 return laraveltest.New(t, bootstrap.Options(), with...)
8}

The seeders run right after the migrations rebuild a copy, and their rows are committed. 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 seeders run again when your code or tests change, and they run without the test's fakes.

The tests of a package share one copy, so every test of a package needs the same SeedOnce, which is why tests.New is the place for it. A test that passes other seeders fails and says which seeders the copy has.

Both Seed and SeedOnce need RefreshDatabase, so a test can't write seed data to your development database.

Database assertions

To check what your application wrote, use AssertDatabaseHas and the other database assertions on the client. Each one reads the table through the client's transaction:

1func TestCancellingAnImportFailsIt(t *testing.T) {
2 client := tests.New(t)
3 
4 client.Post("/imports/7/cancel", nil).AssertRedirect("/imports")
5 
6 client.AssertDatabaseHas("imports", db.Values{"id": 7, "status": "failed"})
7 client.AssertDatabaseMissing("imports", db.Values{"id": 7, "failed_at": nil})
8 client.AssertDatabaseEmpty("import_chunks")
9}
1func TestCancellingAnImportFailsIt(t *testing.T) {
2 client := tests.New(t)
3 
4 client.Post("/imports/7/cancel", nil).AssertRedirect("/imports")
5 
6 client.AssertDatabaseHas("imports", db.Values{"id": 7, "status": "failed"})
7 client.AssertDatabaseMissing("imports", db.Values{"id": 7, "failed_at": nil})
8 client.AssertDatabaseEmpty("import_chunks")
9}
Assertion Asserts
AssertDatabaseHas(table, values) That a row has all the given column values
AssertDatabaseMissing(table, values) That no row has all the given column values
AssertDatabaseCount(table, count) That the table has exactly count rows
AssertDatabaseEmpty(table) That the table has no rows
AssertModelExists(&model) That the model's row exists, found by its ID
AssertModelMissing(&model) That the model's row doesn't exist

A nil value matches NULL. When AssertDatabaseHas fails, it shows the table's first rows, so you can see what your application wrote instead.

The assertions read your default database. If your application writes to a named connection, such as audit rows in a reporting database, call OnConnection with the connection's name first:

1client.OnConnection("reporting").AssertDatabaseCount("audits", 1)
1client.OnConnection("reporting").AssertDatabaseCount("audits", 1)

You may also load a model with client.Context() and check its fields yourself, which is often clearer for dates and computed values:

1imported, err := model.Find[models.Import](client.Context(), importID)
2if err != nil {
3 t.Fatal(err)
4}
5 
6if imported.FailedAt == nil {
7 t.Error("the import has no failed_at time")
8}
1imported, err := model.Find[models.Import](client.Context(), importID)
2if err != nil {
3 t.Fatal(err)
4}
5 
6if imported.FailedAt == nil {
7 t.Error("the import has no failed_at time")
8}

Fakes

Instead of calling external APIs, sending real emails, or running external processes in your tests, Laravel provides fakes that record what your application sent so you can check it. Build the client first, then pass it to each fake's New, which installs the fake in that client's application and returns it. Once the request has run, check what it sent with the fake's own assertions:

1func TestPlacingAnOrder(t *testing.T) {
2 client := tests.New(t)
3 dispatched := eventtest.New(client)
4 emails := mailtest.New(client)
5 
6 client.Post("/orders", url.Values{"total": {"2500"}}).AssertRedirect("/orders")
7 
8 emails.AssertSent[mails.OrderConfirmed]()
9 dispatched.AssertDispatched[events.OrderPlaced]()
10}
1func TestPlacingAnOrder(t *testing.T) {
2 client := tests.New(t)
3 dispatched := eventtest.New(client)
4 emails := mailtest.New(client)
5 
6 client.Post("/orders", url.Values{"total": {"2500"}}).AssertRedirect("/orders")
7 
8 emails.AssertSent[mails.OrderConfirmed]()
9 dispatched.AssertDispatched[events.OrderPlaced]()
10}

Each subsystem's guide covers its fake and assertions:

A few fakes change what a request reads rather than what it sends. The laraveltest.FakeDisk("public") option replaces storage disks with temporary directories, and feature.Fake(client.Context(), features.NewAPI, true) pins a feature flag to a value.

An application holds one fake of each kind, so a second call to the same package's New for one client fails the test. Keep the fake that the first call returned.

Replacing dependencies

To test code that talks to an external system, such as a payment provider, replace the service your application uses with one that doesn't leave your process. Your handlers and jobs get their services from services.From(ctx), which returns the services that services.New built for the application. Each test builds its own application, so a test may replace a service and has nothing to swap back afterwards.

If the service sends its requests with Laravel's HTTP client, fake them with httpclienttest, as Fakes shows. For a client that makes its own requests, such as a provider's SDK, point it at a server your test starts. For example, say your billing.Client calls a provider at the address in its BaseURL field. This test starts a fake provider with the standard library's httptest package, and sets the Billing field of the services that services.From(client.Context()) returns:

1package feature_test
2 
3import (
4 "io"
5 "net/http"
6 "net/http/httptest"
7 "testing"
8 
9 "app/billing"
10 "app/services"
11 "app/tests"
12)
13 
14func TestInvoicesAreListed(t *testing.T) {
15 provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
16 io.WriteString(w, `[{"id": 1, "total": 4200}]`)
17 }))
18 t.Cleanup(provider.Close)
19 
20 billingClient := billing.NewClient("sk_test_key", "usd")
21 billingClient.BaseURL = provider.URL
22 
23 client := tests.New(t)
24 services.From(client.Context()).Billing = billingClient
25 
26 client.Get("/invoices").AssertOK().AssertSee("4200")
27}
1package feature_test
2 
3import (
4 "io"
5 "net/http"
6 "net/http/httptest"
7 "testing"
8 
9 "app/billing"
10 "app/services"
11 "app/tests"
12)
13 
14func TestInvoicesAreListed(t *testing.T) {
15 provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
16 io.WriteString(w, `[{"id": 1, "total": 4200}]`)
17 }))
18 t.Cleanup(provider.Close)
19 
20 billingClient := billing.NewClient("sk_test_key", "usd")
21 billingClient.BaseURL = provider.URL
22 
23 client := tests.New(t)
24 services.From(client.Context()).Billing = billingClient
25 
26 client.Get("/invoices").AssertOK().AssertSee("4200")
27}

The application reads its services on every request, so the next request uses the replacement, and the other services stay as services.New built them.

When a service is an interface, such as a Geocoder that finds the coordinates of an address, your fake can be a small type of its own that implements the interface. This fake returns fixed coordinates and records each address it's asked about, so the test never calls the real geocoding service:

1package feature_test
2 
3import (
4 "context"
5 "slices"
6 "testing"
7 
8 "app/geo"
9 "app/services"
10 "app/tests"
11)
12 
13type fakeGeocoder struct {
14 addresses []string
15}
16 
17func (g *fakeGeocoder) Locate(ctx context.Context, address string) (geo.Coordinates, error) {
18 g.addresses = append(g.addresses, address)
19 
20 return geo.Coordinates{Latitude: 41.8781, Longitude: -87.6298}, nil
21}
22 
23func TestStoresAreFoundNearTheAddress(t *testing.T) {
24 client := tests.New(t)
25 geocoder := &fakeGeocoder{}
26 services.From(client.Context()).Geocoder = geocoder
27 
28 client.Get("/stores?address=Chicago").AssertOK()
29 
30 if !slices.Equal(geocoder.addresses, []string{"Chicago"}) {
31 t.Errorf("geocoded %v, want [Chicago]", geocoder.addresses)
32 }
33}
1package feature_test
2 
3import (
4 "context"
5 "slices"
6 "testing"
7 
8 "app/geo"
9 "app/services"
10 "app/tests"
11)
12 
13type fakeGeocoder struct {
14 addresses []string
15}
16 
17func (g *fakeGeocoder) Locate(ctx context.Context, address string) (geo.Coordinates, error) {
18 g.addresses = append(g.addresses, address)
19 
20 return geo.Coordinates{Latitude: 41.8781, Longitude: -87.6298}, nil
21}
22 
23func TestStoresAreFoundNearTheAddress(t *testing.T) {
24 client := tests.New(t)
25 geocoder := &fakeGeocoder{}
26 services.From(client.Context()).Geocoder = geocoder
27 
28 client.Get("/stores?address=Chicago").AssertOK()
29 
30 if !slices.Equal(geocoder.addresses, []string{"Chicago"}) {
31 t.Errorf("geocoded %v, want [Chicago]", geocoder.addresses)
32 }
33}

Replace a service before the first request that uses it, and don't change it while a request is running.

Time travel

To test what happens later, such as an invitation expiring, move your application's time forward instead of waiting. For example, say your invitation links work for a day:

1package feature_test
2 
3import (
4 "testing"
5 "time"
6 
7 "app/tests"
8)
9 
10func TestInvitationsExpireAfterADay(t *testing.T) {
11 client := tests.New(t)
12 
13 type invitationResponse struct {
14 Link string `json:"link"`
15 }
16 invitation := client.PostJSON("/invitations", nil).AssertCreated().JSON[invitationResponse]()
17 
18 client.Travel(25 * time.Hour)
19 
20 client.Get(invitation.Link).AssertForbidden()
21}
1package feature_test
2 
3import (
4 "testing"
5 "time"
6 
7 "app/tests"
8)
9 
10func TestInvitationsExpireAfterADay(t *testing.T) {
11 client := tests.New(t)
12 
13 type invitationResponse struct {
14 Link string `json:"link"`
15 }
16 invitation := client.PostJSON("/invitations", nil).AssertCreated().JSON[invitationResponse]()
17 
18 client.Travel(25 * time.Hour)
19 
20 client.Get(invitation.Link).AssertForbidden()
21}

Travel moves the time forward by a time.Duration. After it travels, the application's time stands still until you call TravelBack. Each method returns the client, so you may chain a request after it. You may also call these methods:

  • TravelTo(t) travels to a time.Time. For a month or a year, add it to the current time, as in client.TravelTo(client.Now().AddDate(0, 1, 0)).
  • Now() returns the application's current time, for building times that your application compares with its own, such as a post scheduled two hours from now: client.Now().Add(2 * time.Hour).
  • Freeze() stops time where it is.
  • FreezeSecond() 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.
  • TravelBack() returns to the present.

Laravel reads the moved time wherever it checks a time, such as for sessions, cache values, signed URLs, rate limits, delayed jobs, and model timestamps. Each test's application has its own clock, so tests running in parallel don't move each other's time. In your own code, read the time with date.Now(ctx) rather than time.Now(), so tests can move it.

Calling your code directly

Some code is easier to test by calling it directly than through a request, such as a listener, a model's hook, or a function that ranks posts. Call it as you would any Go function, and where it takes a context, pass client.Context(). That context carries the client's application, so your code reaches the same configuration, services, and fakes as the client's requests do, and its queries run in the client's transaction.

For example, say your application has a digest package with a function that returns a user's most-voted posts:

1package digest
2 
3import (
4 "context"
5 
6 "go.laravel.com/model"
7 
8 "app/models"
9)
10 
11func PopularPosts(ctx context.Context, user models.User) ([]models.Post, error) {
12 return model.Query[models.Post]().WhereEq("user_id", user.ID).OrderByDesc("votes").Limit(5).Get(ctx)
13}
1package digest
2 
3import (
4 "context"
5 
6 "go.laravel.com/model"
7 
8 "app/models"
9)
10 
11func PopularPosts(ctx context.Context, user models.User) ([]models.Post, error) {
12 return model.Query[models.Post]().WhereEq("user_id", user.ID).OrderByDesc("votes").Limit(5).Get(ctx)
13}

This test creates two posts, then calls the function with the client's context:

1package feature_test
2 
3import (
4 "testing"
5 
6 "app/database/factories"
7 "app/digest"
8 "app/models"
9 "app/tests"
10)
11 
12func TestPopularPostsStartWithTheMostVoted(t *testing.T) {
13 client := tests.New(t)
14 user := client.Create(factories.User)
15 client.Create(factories.Post.For("user", user), func(p *models.Post) { p.Votes = 10 })
16 popular := client.Create(factories.Post.For("user", user), func(p *models.Post) { p.Votes = 150 })
17 
18 posts, err := digest.PopularPosts(client.Context(), user)
19 if err != nil {
20 t.Fatal(err)
21 }
22 
23 if len(posts) != 2 || posts[0].ID != popular.ID {
24 t.Errorf("got %v, want the post with 150 votes first", posts)
25 }
26}
1package feature_test
2 
3import (
4 "testing"
5 
6 "app/database/factories"
7 "app/digest"
8 "app/models"
9 "app/tests"
10)
11 
12func TestPopularPostsStartWithTheMostVoted(t *testing.T) {
13 client := tests.New(t)
14 user := client.Create(factories.User)
15 client.Create(factories.Post.For("user", user), func(p *models.Post) { p.Votes = 10 })
16 popular := client.Create(factories.Post.For("user", user), func(p *models.Post) { p.Votes = 150 })
17 
18 posts, err := digest.PopularPosts(client.Context(), user)
19 if err != nil {
20 t.Fatal(err)
21 }
22 
23 if len(posts) != 2 || posts[0].ID != popular.ID {
24 t.Errorf("got %v, want the post with 150 votes first", posts)
25 }
26}

For code that reads the logged-in user with auth.User, take the context from a client that acts as the user: client.ActingAs(&user).Context(). To run one attempt of a queued job as a worker would, through its middleware, use client.Attempt, which the queues guide's section on testing a job covers.

Pass client.Context(), not t.Context() or context.Background(). Those don't carry an application, so Laravel's functions panic and tell you which context to pass.

Testing console commands

To run a console command in a test, call the client's Command with the command line as you'd type it after laravel. The command runs in the client's application and transaction, and Laravel captures its output and exit status for you to check:

1func TestStaleDraftsArePruned(t *testing.T) {
2 client := tests.New(t)
3 
4 client.Command("posts:prune --days=30").
5 AssertSuccessful().
6 AssertErrorOutputContains("Deleted 2 drafts.")
7}
1func TestStaleDraftsArePruned(t *testing.T) {
2 client := tests.New(t)
3 
4 client.Command("posts:prune --days=30").
5 AssertSuccessful().
6 AssertErrorOutputContains("Deleted 2 drafts.")
7}

Results from Line and Table go to standard output, so check them with AssertOutputContains. Messages from Info, Success, Warn, and Error, and the error that Run returns, go to standard error, so check them with AssertErrorOutputContains. You may also check that output is absent with AssertOutputMissing, AssertErrorOutputMissing, and AssertNoOutput.

To answer a command's prompts, pass a laraveltest.Answer for each one, in the order the command asks:

1client.Command("user:create",
2 laraveltest.Answer("What is the user's name?", "Taylor"),
3 laraveltest.Answer("Create the user?", "yes"),
4).AssertSuccessful()
1client.Command("user:create",
2 laraveltest.Answer("What is the user's name?", "Taylor"),
3 laraveltest.Answer("Create the user?", "yes"),
4).AssertSuccessful()

To learn more, check out the console guide's section on testing commands.