Laravel feature and unit tests, with a real app · Part 1 of 6

Testing9 min read

What feature and unit mean in Laravel, and the foundation

A fresh Laravel 13 app with Pest 5, the test configuration the installer wrote and why each line matters, the invoicing domain, a hand-written login, and the first twenty tests.

By Abhishek Fouzdar · Updated

This part ends with a fresh Laravel 13 app, Pest 5, the tables InvoiceMini needs, a login, and twenty tests that pass in under a second. Along the way it settles what "feature" and "unit" mean here, because the two words carry more argument than they deserve. The series introduction explains what InvoiceMini is.

Two words

Laravel gives you two folders and a definition for each.

A unit test exercises one class with plain PHP values. It does not boot the framework: no container, no facades, no database, no config. If the class under test needs any of those, it is not a unit test by this definition, whatever its folder says. Unit tests are fast because they skip the boot, and honest because nothing can leak in from a service provider.

A feature test boots the application and goes through it the way a request would: a route, a controller, validation, a policy, a query, a response. It may run a job, send mail, or call an artisan command. The database is real, usually SQLite in memory, and is reset between tests.

The folder is just a folder. What decides which kind of test you are writing is whether the test needs the application. Laravel's own tests/Unit/ExampleTest.php asserts that true is true, and the base class Pest binds to tests/Feature is the one that boots the app. Model logic is the grey area: a method on Invoice that reads a relation needs the database, so its test boots the app and is a feature test however small it looks. The series keeps the business arithmetic out of models for exactly that reason, and part 2 shows what that buys.

Browser tests are a third kind, in a third folder, and get part 6.

Create the app

The Laravel installer asks for a starter kit, a test framework and a database. The answers are flags:

composer global require laravel/installer
laravel new laravel-testing-guide --pest --database=sqlite --git --npm --no-boost --no-interaction
cd laravel-testing-guide
php artisan --version
Laravel Framework 13.38.0

No starter kit, because the point is to test code you wrote, and a hand-written login is thirty lines. --pest installs pestphp/pest, pestphp/pest-plugin-laravel and a tests/Pest.php. --git makes the first two commits for you. On this machine the installer finished without a node_modules folder despite --npm, so npm install && npm run build came next; if npm run build says vite: not found, that is why.

Look at what the installer wrote before writing anything yourself. phpunit.xml is the file that makes tests fast and isolated, and it is where you will add every environment variable the suite needs. Trimmed to the lines that matter:

<php>
    <env name="APP_ENV" value="testing"/>
    <env name="BCRYPT_ROUNDS" value="4"/>
    <env name="CACHE_STORE" value="array"/>
    <env name="DB_CONNECTION" value="sqlite"/>
    <env name="DB_DATABASE" value=":memory:"/>
    <env name="MAIL_MAILER" value="array"/>
    <env name="QUEUE_CONNECTION" value="sync"/>
    <env name="SESSION_DRIVER" value="array"/>
</php>

Each line is a decision. The database is SQLite in memory, created fresh for each test process. Mail goes to an array so nothing is sent and everything can be asserted. The queue is synchronous, so a dispatched job runs inside the request that dispatched it; part 4 leans on that. Bcrypt uses 4 rounds instead of 12, which is why creating a user in a test costs a millisecond instead of eighty. Pest reads this file: Pest 5 is a layer on PHPUnit 13, and phpunit.xml is still the configuration.

tests/Pest.php is Pest's own entry point. The stock one binds tests/Feature to Laravel's TestCase and leaves RefreshDatabase commented out. Mine, after trimming the boilerplate:

<?php

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

// Every test under tests/Feature boots the application and starts from an empty, migrated
// database. Tests under tests/Unit get plain PHPUnit: no container, no database.
pest()->extend(TestCase::class)
    ->use(RefreshDatabase::class)
    ->in('Feature');

RefreshDatabase migrates once per process and wraps each test in a transaction that is rolled back afterwards. With an in-memory database that is the whole cost of isolation. Nothing binds tests/Unit, so a test there gets PHPUnit's bare TestCase, and a call to config() or a facade in it fails with a clear error instead of quietly booting the app.

Run what you have:

./vendor/bin/pest
   PASS  Tests\Unit\ExampleTest
  ✓ that true is true

   PASS  Tests\Feature\ExampleTest
  ✓ the application returns a successful response                        0.12s

  Tests:    2 passed (2 assertions)
  Duration: 0.19s

If instead you see one line of JSON, {"tool":"pest","result":"passed","tests":2,...}, you are running inside an AI coding agent. Laravel 13's skeleton includes laravel/pao, which replaces the output with a compact form whenever it detects one through an environment variable such as AI_AGENT or CLAUDECODE. The humans in the room get the normal output with PAO_DISABLE=1 ./vendor/bin/pest. Every output in this series was captured that way.

The domain

InvoiceMini needs six tables. The migrations are in the part 1 commit; the shape matters more than the code.

Table What it holds
companies Name, currency, default tax rate, payment terms in days, invoice prefix. Every user belongs to one.
users The stock table plus company_id.
clients Belong to a company. Name, email, country, currency.
invoices Company, client, a nullable number, a status, currency, issue and due dates, discount percent, notes, and four stored totals.
invoice_lines Description, quantity, unit price, tax rate, position.
payments Invoice, amount, currency, provider, a unique provider reference, paid at.

Two decisions shape every test that follows. Money is stored in minor units as integers: 1,224.00 euro is 122400. Floats cannot represent 0.10, and a suite full of toBe(12.24) assertions on floats is a suite that fails on a Tuesday. The number is nullable because a draft has none; it is assigned when the invoice is sent, in part 3, and the sequence is part of what the tests have to protect.

Laravel 13 writes models with attributes instead of properties. The stock User has #[Fillable(['name', 'email', 'password'])] above the class, and company_id goes into that list; the other models follow the same style. The status is a backed enum, and it is the first thing worth a unit test:

enum InvoiceStatus: string
{
    case Draft = 'draft';
    case Sent = 'sent';
    case Paid = 'paid';
    case Void = 'void';

    /** The statuses an invoice may move to from this one. */
    public function transitions(): array
    {
        return match ($this) {
            self::Draft => [self::Sent],
            self::Sent => [self::Paid, self::Void],
            self::Paid, self::Void => [],
        };
    }

    public function canTransitionTo(self $next): bool
    {
        return in_array($next, $this->transitions(), true);
    }

    public function label(): string
    {
        return ucfirst($this->value);
    }
}

The first unit test

A status transition needs no application, so its test lives in tests/Unit and runs without one:

<?php

use App\Enums\InvoiceStatus;

it('allows the transitions of a real invoice lifecycle', function (InvoiceStatus $from, InvoiceStatus $to) {
    expect($from->canTransitionTo($to))->toBeTrue();
})->with([
    'draft to sent' => [InvoiceStatus::Draft, InvoiceStatus::Sent],
    'sent to paid' => [InvoiceStatus::Sent, InvoiceStatus::Paid],
    'sent to void' => [InvoiceStatus::Sent, InvoiceStatus::Void],
]);

it('refuses transitions that would rewrite history', function (InvoiceStatus $from, InvoiceStatus $to) {
    expect($from->canTransitionTo($to))->toBeFalse();
})->with([
    'paid to anything' => [InvoiceStatus::Paid, InvoiceStatus::Sent],
    'void to anything' => [InvoiceStatus::Void, InvoiceStatus::Draft],
    'draft straight to paid' => [InvoiceStatus::Draft, InvoiceStatus::Paid],
    'sent back to draft' => [InvoiceStatus::Sent, InvoiceStatus::Draft],
    'draft to void, drafts are deleted instead' => [InvoiceStatus::Draft, InvoiceStatus::Void],
]);

Three Pest ideas in twenty lines. it() takes a sentence and a closure; the sentence is the test's name in the output, so write it as a claim about the code. expect($value)->toBeTrue() is the expectation API, a fluent wrapper over PHPUnit's assertions. ->with([...]) is a dataset: the closure runs once per entry, each entry's key names the case in the output, and a failure says which case broke. The same test in PHPUnit is a class with a method and a #[DataProvider]; nothing changes underneath, and ./vendor/bin/pest runs both styles side by side if you have old tests.

The last dataset entry carries a story. My first version of the enum let a draft be voided. A feature test in part 3 asserted that a draft page showed no Void button, and failed, because the policy correctly offered to void anything the enum allowed. The test had found a modelling disagreement: drafts are deleted, voiding is for invoices a client has seen. The enum changed, this dataset gained a line, and the Void button went away. That is the job: tests that encode decisions, so the next change has to argue with them.

A login worth testing

Without a starter kit the login is a controller, two routes and a view. The controller is Laravel's own recipe:

public function store(Request $request): RedirectResponse
{
    $credentials = $request->validate([
        'email' => ['required', 'email'],
        'password' => ['required'],
    ]);

    if (! Auth::attempt($credentials, $request->boolean('remember'))) {
        return back()
            ->withInput($request->only('email'))
            ->withErrors(['email' => 'These credentials do not match our records.']);
    }

    $request->session()->regenerate();

    return redirect()->intended(route('invoices.index'));
}

Its tests are feature tests: they post to a route and look at the session, the redirect and the guard.

<?php

use App\Models\User;

it('logs a user in with valid credentials and sends them to their invoices', function () {
    $user = User::factory()->create(['password' => 'secret-password']);

    $this->post('/login', ['email' => $user->email, 'password' => 'secret-password'])
        ->assertRedirect('/invoices');

    $this->assertAuthenticatedAs($user);
});

it('rejects a wrong password without revealing which field was wrong', function () {
    $user = User::factory()->create(['password' => 'secret-password']);

    $this->from('/login')
        ->post('/login', ['email' => $user->email, 'password' => 'nope'])
        ->assertRedirect('/login')
        ->assertSessionHasErrors(['email' => 'These credentials do not match our records.']);

    $this->assertGuest();
});

it('validates the form before touching the guard', function (array $input, string $field) {
    $this->post('/login', $input)->assertSessionHasErrors($field);
})->with([
    'missing email' => [['password' => 'x'], 'email'],
    'malformed email' => [['email' => 'not-an-email', 'password' => 'x'], 'email'],
    'missing password' => [['email' => '[email protected]'], 'password'],
]);

it('logs out and invalidates the session', function () {
    $user = User::factory()->create();

    $this->actingAs($user)->post('/logout')->assertRedirect('/login');

    $this->assertGuest();
});

Inside a feature test, $this is the Laravel test case, and $this->post() sends a request through the whole stack and returns a TestResponse whose assertions chain. A few of them do most of the work in any suite. assertRedirect() checks the status and the Location header. assertSessionHasErrors() reads the error bag the redirect carried; given a string it checks the field has an error, given a key and message it checks the message. from('/login') sets the referer so back() has somewhere to go; without it, back() redirects to / and the assertion fails for a reason that has nothing to do with the login. assertAuthenticatedAs() and assertGuest() ask the guard, which is the thing the test is about.

The password in create(['password' => 'secret-password']) is hashed by the model's hashed cast, so the test posts the plain string and the guard compares. The factory's default password is also password, hashed once per run and reused, which is what the cheap BCRYPT_ROUNDS is for.

The first scoping test

The invoices index lists the user's company's invoices. The test that matters is the one that proves it lists nobody else's:

it('lists only the invoices of the user\'s own company', function () {
    $company = Company::factory()->create();
    $user = User::factory()->for($company)->create();
    $mine = Invoice::factory()->for($company)->sent()->create(['number' => 'INV-0001']);
    $theirs = Invoice::factory()->sent()->create(['number' => 'INV-9999']);

    $this->actingAs($user)
        ->get('/invoices')
        ->assertOk()
        ->assertSee($mine->number)
        ->assertDontSee($theirs->number);
});

Every multi-tenant feature gets one of these, and the pattern is always the same: one record that should appear, one that should not, created by a factory that makes its own company when you do not hand it one. assertSee() searches the response body for an escaped string; assertDontSee() is the half that catches the bug. The factories and their sent() state are in the commit, and part 5 goes through what makes them short to use.

Run it

./vendor/bin/pest
   PASS  Tests\Unit\InvoiceStatusTest
  ✓ it allows the transitions of a real invoice lifecycle with dataset "draft to sent"
  ✓ it allows the transitions of a real invoice lifecycle with dataset "sent to paid"
  ✓ it allows the transitions of a real invoice lifecycle with dataset "sent to void"
  ✓ it refuses transitions that would rewrite history with dataset "paid to anything"
  ...
   PASS  Tests\Feature\Auth\LoginTest
  ✓ it shows the login page to guests                                    0.20s
  ✓ it logs a user in with valid credentials and sends them to their in… 0.03s
  ✓ it rejects a wrong password without revealing which field was wrong  0.21s
  ...
   PASS  Tests\Feature\InvoicesIndexTest
  ✓ it requires a login                                                  0.01s
  ✓ it lists only the invoices of the user's own company                 0.02s
  ✓ it shows an empty state when there is nothing to bill yet            0.01s

  Tests:    20 passed (40 assertions)
  Duration: 0.62s

The unit tests have no timing because there is nothing to time. The two slowest feature tests are the ones that render the login page the first time and hash a wrong password; everything else is a hundredth of a second. Twenty tests, 0.6 seconds, and that ratio holds as the suite grows, which is part 5's subject.

The part 1 commit has the migrations, models, factories, seeder, views and tests.

What went wrong

Call to undefined method Database\Factories\InvoiceFactory::draft() while seeding. Factory states are ordinary methods; the seeder called one I had not written. The error is clear once you know states are nothing more than that.

vite: not found from npm run build. The installer's --npm flag did not leave a node_modules folder on this machine. npm install first.

Test directory "tests/Unit" not found after deleting the example test with git rm. Git does not track empty folders, so removing the last file removed the folder, and Pest stops rather than guessing. Recreate the folder, or keep a test in it, which is the plan anyway.

A line of JSON instead of test output. The laravel/pao package in the Laravel 13 skeleton, described above. PAO_DISABLE=1 ./vendor/bin/pest from inside an agent, or run tests from a plain terminal.

Part 2 takes the arithmetic that an invoice needs, keeps it out of the models, and tests it with nothing but PHP.

New posts by email

Get new posts by email. Nothing else, no digests, unsubscribe in one click.

Comments

Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.