Laravel feature and unit tests, with a real app · Part 5 of 6
Database, factories, speed and CI
Architecture tests that keep the domain pure, five factory techniques, SQLite against MySQL, parallel runs, coverage and type coverage, and the GitHub Actions workflow that runs it all.
By Abhishek Fouzdar · Updated
This part is about the machinery under the tests: the database they run on and what SQLite forgives, the factories that keep setup to a few lines, architecture tests that hold the design in place, how fast the suite goes in parallel, what coverage and type coverage report, and the GitHub Actions workflow that runs all of it on every push. It ends at 123 tests and a green workflow on two PHP versions and MySQL. Part 4 added the fakes; the series introduction explains InvoiceMini.
Architecture tests: the design, as a test
Part 2 made a rule, nothing under app/Billing except the actions may know Eloquent exists, and a rule nobody enforces lasts until the next busy afternoon. Pest's architecture plugin, bundled with Pest, turns it into a test:
<?php
arch()->preset()->php();
arch()->preset()->security();
arch('the billing domain stays pure, so it can be unit tested')
->expect('App\Billing')
->not->toUse(['Illuminate', 'App\Models'])
->ignoring(['App\Billing\Actions', 'App\Billing\ExchangeRates']);
arch('actions are the only place billing meets Eloquent')
->expect('App\Models')
->not->toBeUsedIn('App\Billing')
->ignoring('App\Billing\Actions');
arch('controllers')
->expect('App\Http\Controllers')
->toHaveSuffix('Controller')
->toExtend('App\Http\Controllers\Controller');
arch('jobs and queued listeners are serialisable work')
->expect('App\Jobs')
->toImplement('Illuminate\Contracts\Queue\ShouldQueue');
Each preset is one rule with a long list of forbidden functions: php() forbids dump(), var_dump(), print_r(), die and the old mysql_* functions anywhere in app/, security() forbids md5(), sha1(), rand() and friends where a secure function should be. (dd() is on the Laravel preset's list, not this one.) The named rules are the project's own. These tests read the source with reflection and never boot the app, so they live in tests/Unit, and they take about a second because they parse every class once. The ignoring() call goes after the expectation, not before it; the first entry under what went wrong is what happens otherwise.
Factories: the five tools
Every feature test in the series creates a company, a user and a client. How much of each test that takes is decided by the factories, and five techniques keep it short. They are demonstrated in tests/Feature/Database/FactoriesTest.php, which exists to be read.
recycle() shares one model across a graph. Without it, Invoice::factory()->create() makes a company for the invoice and the client factory makes another, and the invoice's client belongs to a company the invoice does not:
$invoice = Invoice::factory()->recycle($company)
->has(InvoiceLine::factory()->count(2), 'lines')
->create();
expect($invoice->company->is($company))->toBeTrue()
->and($invoice->client->company_id)->toBe($company->id)
->and(Company::count())->toBe(1);
Note is() rather than toBe(): two Eloquent instances of the same row are different objects, and toBe() is identity.
Sequences assign attributes across a count(), and the order of states matters:
$invoices = Invoice::factory()->count(3)->recycle($company)->sent()
->sequence(['number' => 'INV-2026-0001'], ['number' => 'INV-2026-0002'], ['number' => 'INV-2026-0003'])
->create();
States apply in the order they were added. sent() sets a number of its own, so the sequence goes after it; the other way round, the state wins and three invoices share a number until the unique index objects.
A named state with children. withLines(3) is has(InvoiceLine::factory()->count(3), 'lines') wrapped in a method, and the factory's configure() adds an afterCreating hook that stores the totals whenever lines exist:
public function configure(): static
{
return $this->afterCreating(function (Invoice $invoice) {
if ($invoice->lines()->exists()) {
$invoice->recalculate();
}
});
}
The hook runs after the children are created, so Invoice::factory()->withLines(3)->create() comes back with totals that match its lines, and the browser tests in part 6 use nothing else.
make() does not save the model, but it does save the parents its definition names. User::factory()->make() leaves users empty and companies with one row, because 'company_id' => Company::factory() in the definition is resolved with create() either way. The test in the file asserts both counts, because I expected the second to be zero.
unique() on Faker holds for the whole run. Twenty clients from one factory have twenty different emails; the test asserts it so a future change to the factory cannot break the unique index in some other test an hour later.
SQLite in memory, and what it forgives
The suite runs on SQLite in memory because it is the fastest database that exists and needs nothing installed. Production runs MySQL, and the two disagree in ways that only show up when you run the suite against the real one:
lockForUpdate()is a no-op on SQLite. Part 3's number lookup relies on it under concurrency; SQLite cannot test that.- Foreign keys are enforced on MySQL always and on SQLite only when the connection turns them on, which Laravel does by default, but a
restrictOnDelete()that works on one and not the other is a bug you want to see. - String comparison is case-insensitive on MySQL's default collation and case-sensitive on SQLite, so a
where('email', ...)test can pass on one and fail on the other. - JSON functions,
whereDate()edge cases andlength()on multi-byte strings differ in small ways.
So the suite also runs on MySQL. Locally that is a container and six environment variables; phpunit.xml values give way to real environment variables, which is the mechanism:
docker run -d --name invoicemini-mysql -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=invoicemini_test -p 127.0.0.1:3310:3306 mysql:8.4
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3310 DB_DATABASE=invoicemini_test DB_USERNAME=root DB_PASSWORD=root ./vendor/bin/pest
Tests: 123 passed (287 assertions)
Duration: 10.00s
Ten seconds against 3.8 on SQLite, same tests. The whole difference is the database. Nothing failed, which is the news you want, and the run goes in CI below so it stays that way.
Faster: parallel
Pest ships ParaTest, and --parallel splits the files across processes:
./vendor/bin/pest --parallel
Tests: 123 passed (287 assertions)
Duration: 2.59s
Parallel: 8 processes
With SQLite in memory each process simply gets its own database. With MySQL, Laravel's parallel testing creates one database per process, invoicemini_test_test_1 through _8, migrates each, and reuses them on the next run:
DB_CONNECTION=mysql ... ./vendor/bin/pest --parallel
Tests: 123 passed (287 assertions)
Duration: 12.71s
Parallel: 8 processes
Slower than serial on this laptop, because eight MySQL connections on a 4-core machine contend for the same disk, while SQLite in memory scales with cores. The runner in CI has two cores and gets the opposite result. Measure before assuming.
Two more flags earn their place. --profile lists the ten slowest tests, and on this suite they are the first render of a page in each process, the PDF, and the tests that hash passwords; nothing surprising, which is itself the finding. --dirty runs only the tests in files with uncommitted changes, according to git, which is the loop you want while writing a test.
Coverage and type coverage
Line coverage needs a driver, pcov or Xdebug, and this laptop has neither, so the numbers below are from CI, where shivammathur/setup-php installs pcov in one line. --coverage prints a per-file table and --min=80 fails the run below a threshold:
Billing/Actions/VoidInvoice ........................ 13 / 75.0%
Http/Controllers/InvoiceController ........... 76..79, 80 / 90.4%
Mail/ReceiptMail ................................ 22..24 / 40.0%
...
Total: 95.5 %
The uncovered lines are the DomainException branch in VoidInvoice, which the policy makes unreachable over HTTP, and the content method of the receipt mail, which no test renders. Both are real gaps and the report found them in a second.
Type coverage is a Pest plugin, pestphp/pest-plugin-type-coverage, and needs no driver: it reads the source and reports every parameter, return and property without a type:
./vendor/bin/pest --type-coverage --min=100
app/Console/Commands/SendOverdueReminders.php ..................... pa23 75%
Total: 99.3 %
pa23 is "parameter, line 23": a fn ($q) => closure in a query. One Builder $q later it is 100%, and the workflow holds it there. On a codebase with types everywhere this is the cheapest check you can add; on one without, it is a map of where to start.
Pest 5 also ships mutation testing behind --mutate, which edits your code and checks that a test fails. It needs a coverage driver, so it is not run in this series; it is the next thing to try on TotalsCalculator.
The workflow
This workflow only tests; the repository is a public demo with nothing to deploy. For the other half, a workflow that deploys on merge with checks that gate it, see GitHub Actions for an existing Laravel app.
.github/workflows/tests.yml runs four jobs on every push and pull request, and part 6 adds a fifth; the full file is in the part 5 commit. What each one is for:
| Job | Runs | Why |
|---|---|---|
| pint | pint --test |
A formatting failure should not wait for the suite. 16 seconds. |
| tests (8.4, 8.5) | Unit and Feature, --parallel --coverage --min=80, then --type-coverage --min=100 |
The suite on the PHP versions Pest 5 supports, with pcov. 24 and 39 seconds. |
| tests-mysql | Unit and Feature, --parallel, against a mysql:8.4 service |
What SQLite forgives. 42 seconds. |
| browser | Part 6. | A real Chromium. |
The PHP jobs install no Node and build no assets. The base test case makes that possible:
protected function setUp(): void
{
parent::setUp();
// Blade's @vite needs a built manifest; tests do not. CI's PHP job has no Node.
$this->withoutVite();
}
@vite throws when the manifest is missing, and the first run of the suite on a clean runner is where you learn that. withoutVite() swaps the directive for nothing; the browser job, which needs the real assets, turns it back on for its own suite.
The MySQL job is the same steps with a service container and the six variables from the local run as job environment. --testsuite=Unit,Feature on the PHP and MySQL jobs keeps the browser suite out of them, because it needs Playwright and gets a job of its own.
Run it
Locally, on SQLite, all of part 5's additions included:
./vendor/bin/pest
Tests: 123 passed (287 assertions)
Duration: 3.78s
And the push:
gh run watch
tests-mysql: success 08:01:55-08:02:37
tests (8.5): success 08:01:55-08:02:19
tests (8.4): success 08:01:55-08:02:34
pint: success 08:01:55-08:02:11
What went wrong
Method [ignoring] does not exist in [string] from the architecture test. expect('App\Billing')->ignoring(...) is wrong; ignoring() modifies the expectation, so it goes after not->toUse(...). The error names a string because at that point the expectation is still just the namespace.
Failed asserting that two variables reference the same object on expect($invoice->company)->toBe($company). Two instances of one row. is() compares keys.
Failed asserting that an instance of class App\Models\Company is null. The make() surprise above. The test now documents it instead of denying it.
Access denied for user 'root'@'172.23.0.1' from the MySQL run, with the right password. Port 3307 on this laptop already belonged to another project's database container, and docker run -p 3307:3306 had quietly failed to bind. The suite was talking to the wrong MySQL. docker ps shows the port owner; the fix was a port nobody else had.
Part 6 opens a real browser.
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.
In this series
5 / 6