← All guides

Published · 5 min read

Testing in Laravel Rust, for Laravel developers

Feature tests, a fresh database per test, factories, validation assertions, swapping services and time travel, translated from PHPUnit and Pest to #[laravel::test].

  • testing
  • database
  • getting-started
On this page
  1. A feature test, before and after
  2. Running tests
  3. The database, per test
  4. Factories
  5. Asserting validation
  6. Logged-in users and guests
  7. Faking a service
  8. Time travel
  9. Test settings
  10. Quick reference

If you write feature tests in Laravel PHP, you already know the shape of a Laravel Rust test: send a request through the whole app, assert on the response, check the database. The test runner is now cargo test, the attribute #[laravel::test] replaces the test class, and a few things you set up by hand in PHP, like RefreshDatabase, are simply on by default.

The app under test sells train seats: a signed-in traveller holds a seat on a departure for ten minutes while they pay.

cargo test runs the train-seat tests in parallel: travellers_can_hold_a_seat, checkout_charges_for_the_held_seat and fares_are_shown_in_euros each get their own database copy (laravel_test_1, laravel_test_2, laravel_test_3), their own services and their own clock, and each runs in a transaction that’s rolled back at the end, so nothing is committed and parallel tests never see each other’s rows.

A feature test, before and after

In Pest, with Laravel PHP:

uses(RefreshDatabase::class);

it('lets a traveller hold a seat', function () {
    $user = User::factory()->create();
    $departure = Departure::factory()->create();

    $this->actingAs($user)
        ->post("/departures/{$departure->id}/holds", ['seat' => '12A'])
        ->assertRedirect("/departures/{$departure->id}/checkout");

    $this->assertDatabaseHas('seat_holds', ['seat' => '12A', 'user_id' => $user->id]);
});

In Laravel Rust:

// tests/seat_holds.rs
use app::models::{Departure, User};
use laravel::testing::prelude::*;

#[laravel::test]
async fn travellers_can_hold_a_seat(app: Application) -> laravel::Result<()> {
    let user = User::factory().create().await?;
    let departure = Departure::factory().create().await?;

    app.post(&format!("/departures/{}/holds", departure.id))
        .form([("seat", "12A")])
        .acting_as(&user)
        .await
        .assert_redirect_to(&format!("/departures/{}/checkout", departure.id));

    app.assert_database_has("seat_holds", json!({ "seat": "12A", "user_id": user.id }))
        .await;

    Ok(())
}

What changed:

  • #[laravel::test] and an Application argument. Asking for app: Application gives the test a fresh app of its own. A test without that argument runs as a plain unit test and boots nothing.
  • No RefreshDatabase line. New apps already call refresh_database() in src/testing.rs. More on that below.
  • The request is built, then awaited. form, json, header and acting_as add to the request; .await sends it and returns a response you assert on.
  • Paths into your app start with app::, whatever the project is called.
  • Test files live in tests/, and run with cargo test.

Running tests

cargo test
cargo test holds        # only tests whose names contain "holds"
cargo nextest run       # also works

Tests run in parallel by default, and they don’t step on each other: each has its own services, its own clock and, with refresh_database, its own database.

The database, per test

refresh_database() gives each running test a numbered copy of your test database (laravel_test_1, laravel_test_2, …), built from your migrations. Every test runs inside a transaction that’s never committed, so whatever it writes disappears when it ends.

The copies are kept between runs and rebuilt only when your application code changes, so you don’t wait for migrations every time. Three things follow from the rollback approach:

  • Auto-increment IDs keep climbing between tests. Assert on the IDs your app returns, never on a hard-coded 1.
  • Create tables in migrations, not in tests. On MySQL, CREATE TABLE commits the transaction.
  • Other processes can’t see the test’s rows, such as a queue worker you start yourself.

On PostgreSQL and MySQL, the database user needs permission to create databases, since Laravel creates the copies.

Factories

Factories look much like Laravel PHP’s. A factory sits next to its model, and the compiler points at it when you add a required column:

let user = User::factory().create().await?;

let departures = Departure::factory()
    .count(3)
    .create()
    .await?;

For a larger fixture set, call a seeder from the test with app.seed(...), or seed every test database once with seed_once in src/testing.rs, which suits reference data such as stations or roles.

Asserting validation

These work for both redirect-back form errors and 422 JSON responses:

app.post(&format!("/departures/{}/holds", departure.id))
    .form([("seat", "")])
    .acting_as(&user)
    .await
    .assert_invalid(&["seat"])
    .assert_invalid_messages(&[("seat", "required")]);

assert_valid(&[...]) checks the opposite, and assert_invalid_in(form, &[...]) handles pages with several named forms.

Logged-in users and guests

acting_as(&user) is actingAs($user). After a login or logout request, assert_authenticated_as(&user) and assert_guest() check the result. For a guest hitting a protected route, assert on the redirect or the status:

app.get("/account/bookings").await.assert_redirect_to("/login");

Faking a service

The checkout calls a payment provider through your own Payments service. Give that service a fake mode that records charges, then swap it into the container before any request uses it:

use app::services::Payments;

#[laravel::test]
async fn checkout_charges_for_the_held_seat(app: Application) -> laravel::Result<()> {
    let payments = app.swap(Payments::fake());
    let user = User::factory().create().await?;

    // ...hold a seat for this user as above, then:
    app.post("/checkout").acting_as(&user).await.assert_redirect();

    payments.assert_charged(4_950);

    Ok(())
}

app.swap returns a handle to the fake so you can assert on it afterwards. This is Laravel PHP’s $this->swap() or instance(), except that the fake is your own code: fake() and assert_charged are methods you write on Payments.

Laravel’s own subsystems come with fakes ready-made: mail::fake(), queue::fake(), event::fake(), notification::fake(), storage::fake(), client::fake() for the HTTP client, and more. Each returns a guard that stays active until it’s dropped, so bind it to a variable: let queue = queue::fake();, not let _ = ....

Time travel

The hold expires after ten minutes. Instead of sleeping, move the test’s clock:

app.travel(11.minutes());

app.post("/checkout").acting_as(&user).await.assert_forbidden();

travel takes any span (11.minutes(), 25.hours()). There’s also travel_to(time), freeze_time() and travel_back(), as in PHP. Each test has its own clock, so parallel tests never shift each other’s time. One rule makes this work: read the time in your app with laravel::now(), not the system clock.

Test settings

src/testing.rs holds the environment overrides for tests: fast bcrypt rounds, in-memory cache and sessions, the log mailer, the sync queue, and so on. It’s the equivalent of the <env> block in phpunit.xml. A .env.testing file is read instead of .env if it exists. For a variant used by only some tests, write a small function that returns a configured Application and name it in the attribute:

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

#[laravel::test(app = app_in_euros)]
async fn fares_are_shown_in_euros(app: Application) {
    app.get("/fares").await.assert_see("€");
}

Quick reference

Laravel PHP Laravel Rust
php artisan test cargo test
uses(RefreshDatabase::class) refresh_database() in src/testing.rs, on by default
$this->actingAs($user) .acting_as(&user)
->post($url, $data) app.post(url).form([...]) or .json(json!({...}))
->assertRedirect($url) .assert_redirect_to(url)
->assertInvalid(['seat']) .assert_invalid(&["seat"])
$this->assertDatabaseHas(...) app.assert_database_has(table, json!({...})).await
$this->travel(11)->minutes() app.travel(11.minutes())
$this->swap(...) app.swap(...)
phpunit.xml <env> src/testing.rs