Lesson 7 of 9 · 24m
Laravel Testing Foundations That Actually Catch Bugs
Feature-first testing, database isolation, factories, and the assertion habits that make Laravel tests useful instead of ceremonial.
Laravel makes testing easy enough that teams can write thousands of worthless tests. The difference is intent: production-grade tests verify behavior users depend on, not framework trivia. In most applications, the center of gravity should be feature tests against real HTTP endpoints and a real test database.
Start at the feature boundary
public function test_customer_can_issue_invoice(): void
{
$customer = Customer::factory()->create();
$user = User::factory()->for($customer)->create();
$this->actingAs($user)
->postJson('/api/invoices', [
'lines' => [
['description' => 'Managed hosting', 'amount' => 12000],
],
])
->assertCreated()
->assertJsonPath('total_cents', 12000);
$this->assertDatabaseHas('invoices', [
'customer_id' => $customer->id,
'total_cents' => 12000,
]);
}This test exercises routing, middleware, validation, authorization, application logic, and persistence together. That is not cheating; that is the behavior the user experiences.
Use factories as executable fixtures
Factories should create valid objects by default:
final class InvoiceFactory extends Factory
{
public function definition(): array
{
return [
'customer_id' => Customer::factory(),
'status' => 'open',
'total_cents' => 0,
];
}
public function paid(): static
{
return $this->state(fn () => ['status' => 'paid']);
}
}If a test needs ten lines of setup to create a valid invoice, future developers will copy those lines into every test until fixture drift makes the suite unreadable. Encode domain states as factory states: paid(), overdue(), fraudReview().
Database isolation choices
RefreshDatabase migrates once and wraps tests in transactions when possible. It is the default for a reason. DatabaseTransactions is faster on an already migrated database but can hide migration errors. SQLite is fast but does not perfectly emulate PostgreSQL behavior — generated columns, strict JSON behavior, locking, and some index types differ. Use SQLite for speed only if CI also runs critical suites against the production database engine.
Unit tests are for dense logic
Pure calculations, parsers, and rule engines deserve focused unit tests. Controllers and thin actions usually do not; feature tests already cover them. Mocking the entire universe to test that a method calls another method verifies your mock setup, not your application.
Field notes
- Use
php artisan test --filter=InvoiceTestwhile iterating; do not wait for the full suite every time. - Freeze time with
Carbon::setTestNow()or Laravel's time helpers when testing expiration behavior. - Assertions should include at least one external effect: database row, queued job, mail, HTTP response, or file. Internal state alone is weak evidence.
- A suite that randomly fails is worse than no suite. Quarantine flakes immediately and treat fixing them as production work.
Was this lesson helpful?