Laravel Testing
Test strategy for a layered Laravel application: 20 rules across 5 sections. Examples use Pest; every rule applies equally to PHPUnit.
The organizing idea: each layer has one test style that fits it. Testing an Action against a real database, or a Query Class against a mock, produces a slow suite that breaks on refactors and misses real bugs.
When to Apply
- Writing tests for any layer defined by the
laravel-patterns skill
- Deciding what to fake and what to run for real
- The suite is slow, flaky, or nobody runs it locally
- Reviewing a pull request's test coverage
- Setting testing conventions for a project
The Layer Table
| Layer |
Style |
Database |
What it proves |
| Action |
Unit, fake repository |
No |
The use case orchestrates correctly |
| Service |
Unit, fakes |
No |
The business decision is right |
| Repository |
Integration, factories |
Yes |
Methods return the right domain types |
| Query Class |
Integration, factories |
Yes |
Which rows are in, out, and in what order |
| Value Object |
Pure unit |
No |
Predicates and transformations |
| Controller / route |
Feature test |
Usually |
Status, payload, authorization |
| Job / Listener |
Unit handler, faked dispatch |
Depends |
Idempotency and effects |
Pick the Rule
| About to write |
Read |
| A test for anything at all |
strategy-layer-to-test-type, strategy-test-your-rules-not-the-framework |
| A test that needs a Repository |
fake-repository-anonymous-class, fake-never-mock-eloquent |
| A test for a Query Class |
db-refresh-database-and-factories, db-assert-inclusion-and-exclusion |
| A test for ordering or defaults |
db-test-ordering-and-defaults |
| A test for an endpoint |
http-assert-payload-shape, http-assert-authorization |
| A test that a job or event fired |
http-assert-side-effects-dispatched, fake-framework-facades |
| A test involving dates or randomness |
fake-time-and-randomness |
| A test for a Value Object |
vo-test-predicates-directly, vo-never-hand-a-builder |
| A test for code that calls an API |
fake-http-prevent-stray-requests |
| A test for queued mail or notifications |
fake-assert-queued-not-sent |
| A test that feels pointless to write |
strategy-if-testing-feels-silly |
Before You Write Code
- Every API named in these rules is verified against Laravel
^12.0 || ^13.0 and PHP ^8.3. If you need something these rules do not name, check the docs — never infer an API from its name.
- Version-gated APIs are marked inline ("Laravel 13 only"). Read the project's
composer.json first; on Laravel 12 use the fallback the rule gives.
- Where the project already differs from a rule, follow the project. Name the rule you set aside and why, rather than half-converting the codebase.
- When two rules collide, the higher-impact section wins — sections are ordered by impact.
- One example is not the whole rule. Open
rules/{slug}.md before adapting it to a case the example does not show.
Rule Sections by Priority
| # |
Section |
Impact |
Prefix |
| 1 |
Strategy by Layer |
HIGH |
strategy- |
| 2 |
Fakes and Doubles |
HIGH |
fake- |
| 3 |
Database Tests |
HIGH |
db- |
| 4 |
Feature Tests |
MEDIUM-HIGH |
http- |
| 5 |
Value Object Tests |
MEDIUM |
vo- |
Quick Reference
1. Strategy by Layer (HIGH)
strategy-layer-to-test-type — Match the test style to the layer
strategy-test-your-rules-not-the-framework — Test your rules, not Eloquent
strategy-if-testing-feels-silly — A pointless test means a pointless class
strategy-pest-and-suite-speed — Keep the suite fast enough to run on every save
2. Fakes and Doubles (HIGH)
fake-repository-anonymous-class — Fake a Repository with an anonymous class
fake-framework-facades — Queue::fake(), Event::fake(), Http::fake() and friends
fake-never-mock-eloquent — Never mock Eloquent or the query builder
fake-time-and-randomness — Freeze time, seed randomness
fake-http-prevent-stray-requests — Fake the HTTP client and forbid stray requests
fake-assert-queued-not-sent — assertQueued() for anything ShouldQueue
3. Database Tests (HIGH)
db-refresh-database-and-factories — RefreshDatabase plus factories, never shared fixtures
db-assert-inclusion-and-exclusion — Assert what is excluded, not only what is included
db-test-ordering-and-defaults — Cover ordering, defaults and the sort allow-list
db-test-eager-loading — Lock the N+1 fix in place
db-test-transactions-and-idempotency — Prove rollback and repeat-safety
4. Feature Tests (MEDIUM-HIGH)
http-assert-authorization — Unauthenticated, unpermitted, and another tenant's record
http-assert-payload-shape — Pin the contract, including keys that must not appear
http-assert-side-effects-dispatched — Assert the jobs and events an endpoint queues
5. Value Object Tests (MEDIUM)
vo-test-predicates-directly — Construct, call, assert — no database, no container
vo-never-hand-a-builder — A test needing a Builder means the boundary is broken
Suite Configuration
// tests/Pest.php
uses(Tests\TestCase::class, RefreshDatabase::class)->in('Feature', 'Integration');
uses(Tests\TestCase::class)->in('Unit'); // no database
<!-- phpunit.xml -->
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="CACHE_STORE" value="array"/>
<env name="MAIL_MAILER" value="array"/>
// AppServiceProvider::boot() — makes N+1 and typos fail the suite
Model::shouldBeStrict(! $this->app->isProduction());
SQLite differs from MySQL and Postgres on JSON operators, full-text search, locking and strict-mode errors. Run the integration suite against the production engine in CI even when local runs use SQLite.
Reference Material
references/test-templates.md — copy-paste starting points for each layer
references/checklist.md — pre-merge self-check for test coverage
How to Use
Load in this order and stop when the answer is clear:
- This file — the Quick Reference names every rule, and usually settles the question.
- One rule file for the reasoning and both examples (~465 tokens each):
rules/fake-repository-anonymous-class.md
rules/db-assert-inclusion-and-exclusion.md
- A
references/ file only when a rule points at one.
AGENTS.md is every rule compiled into one document (~8k tokens), for agents that read the AGENTS.md convention. Do not load it when the individual rule files are reachable.
Related Skills
laravel-engineering — decide which changed boundary needs proof and keep docs current
laravel-patterns — the layers these tests are organized around
laravel-eloquent — the query rules the database tests assert
laravel-rest-api — the endpoints the feature tests cover
laravel-async — testing idempotency, batches and cache invalidation
1---2name: laravel-testing3description: Test strategy for a layered Laravel application — which test style fits each layer, hand-written fakes over mocks, real-database tests for Query Classes and Repositories, pure tests for Value Objects, and feature tests that assert authorization, payload shape and query counts. Use when writing or reviewing Laravel tests, deciding what to fake, diagnosing a flaky or slow suite, or setting a project's testing conventions.4license: MIT5---67# Laravel Testing89Test strategy for a layered Laravel application: 20 rules across 5 sections. Examples use Pest; every rule applies equally to PHPUnit.1011The organizing idea: **each layer has one test style that fits it.** Testing an Action against a real database, or a Query Class against a mock, produces a slow suite that breaks on refactors and misses real bugs.1213## When to Apply1415- Writing tests for any layer defined by the `laravel-patterns` skill16- Deciding what to fake and what to run for real17- The suite is slow, flaky, or nobody runs it locally18- Reviewing a pull request's test coverage19- Setting testing conventions for a project2021## The Layer Table2223| Layer | Style | Database | What it proves |24|-------|-------|----------|----------------|25| Action | Unit, fake repository | No | The use case orchestrates correctly |26| Service | Unit, fakes | No | The business decision is right |27| Repository | Integration, factories | Yes | Methods return the right domain types |28| Query Class | Integration, factories | Yes | Which rows are in, out, and in what order |29| Value Object | Pure unit | No | Predicates and transformations |30| Controller / route | Feature test | Usually | Status, payload, authorization |31| Job / Listener | Unit handler, faked dispatch | Depends | Idempotency and effects |3233## Pick the Rule3435| About to write | Read |36|----------------|------|37| A test for anything at all | `strategy-layer-to-test-type`, `strategy-test-your-rules-not-the-framework` |38| A test that needs a Repository | `fake-repository-anonymous-class`, `fake-never-mock-eloquent` |39| A test for a Query Class | `db-refresh-database-and-factories`, `db-assert-inclusion-and-exclusion` |40| A test for ordering or defaults | `db-test-ordering-and-defaults` |41| A test for an endpoint | `http-assert-payload-shape`, `http-assert-authorization` |42| A test that a job or event fired | `http-assert-side-effects-dispatched`, `fake-framework-facades` |43| A test involving dates or randomness | `fake-time-and-randomness` |44| A test for a Value Object | `vo-test-predicates-directly`, `vo-never-hand-a-builder` |45| A test for code that calls an API | `fake-http-prevent-stray-requests` |46| A test for queued mail or notifications | `fake-assert-queued-not-sent` |47| A test that feels pointless to write | `strategy-if-testing-feels-silly` |4849## Before You Write Code5051- Every API named in these rules is verified against Laravel `^12.0 || ^13.0` and PHP `^8.3`. If you need something these rules do not name, check the docs — never infer an API from its name.52- Version-gated APIs are marked inline ("Laravel 13 only"). Read the project's `composer.json` first; on Laravel 12 use the fallback the rule gives.53- Where the project already differs from a rule, follow the project. Name the rule you set aside and why, rather than half-converting the codebase.54- When two rules collide, the higher-impact section wins — sections are ordered by impact.55- One example is not the whole rule. Open `rules/{slug}.md` before adapting it to a case the example does not show.5657## Rule Sections by Priority5859| # | Section | Impact | Prefix |60|---|---------|--------|--------|61| 1 | Strategy by Layer | HIGH | `strategy-` |62| 2 | Fakes and Doubles | HIGH | `fake-` |63| 3 | Database Tests | HIGH | `db-` |64| 4 | Feature Tests | MEDIUM-HIGH | `http-` |65| 5 | Value Object Tests | MEDIUM | `vo-` |6667## Quick Reference6869### 1. Strategy by Layer (HIGH)7071- `strategy-layer-to-test-type` — Match the test style to the layer72- `strategy-test-your-rules-not-the-framework` — Test your rules, not Eloquent73- `strategy-if-testing-feels-silly` — A pointless test means a pointless class74- `strategy-pest-and-suite-speed` — Keep the suite fast enough to run on every save7576### 2. Fakes and Doubles (HIGH)7778- `fake-repository-anonymous-class` — Fake a Repository with an anonymous class79- `fake-framework-facades` — `Queue::fake()`, `Event::fake()`, `Http::fake()` and friends80- `fake-never-mock-eloquent` — Never mock Eloquent or the query builder81- `fake-time-and-randomness` — Freeze time, seed randomness82- `fake-http-prevent-stray-requests` — Fake the HTTP client and forbid stray requests83- `fake-assert-queued-not-sent` — `assertQueued()` for anything `ShouldQueue`8485### 3. Database Tests (HIGH)8687- `db-refresh-database-and-factories` — `RefreshDatabase` plus factories, never shared fixtures88- `db-assert-inclusion-and-exclusion` — Assert what is excluded, not only what is included89- `db-test-ordering-and-defaults` — Cover ordering, defaults and the sort allow-list90- `db-test-eager-loading` — Lock the N+1 fix in place91- `db-test-transactions-and-idempotency` — Prove rollback and repeat-safety9293### 4. Feature Tests (MEDIUM-HIGH)9495- `http-assert-authorization` — Unauthenticated, unpermitted, and another tenant's record96- `http-assert-payload-shape` — Pin the contract, including keys that must not appear97- `http-assert-side-effects-dispatched` — Assert the jobs and events an endpoint queues9899### 5. Value Object Tests (MEDIUM)100101- `vo-test-predicates-directly` — Construct, call, assert — no database, no container102- `vo-never-hand-a-builder` — A test needing a `Builder` means the boundary is broken103104## Suite Configuration105106```php107// tests/Pest.php108uses(Tests\TestCase::class, RefreshDatabase::class)->in('Feature', 'Integration');109uses(Tests\TestCase::class)->in('Unit'); // no database110```111112```xml113<!-- phpunit.xml -->114<env name="DB_CONNECTION" value="sqlite"/>115<env name="DB_DATABASE" value=":memory:"/>116<env name="QUEUE_CONNECTION" value="sync"/>117<env name="CACHE_STORE" value="array"/>118<env name="MAIL_MAILER" value="array"/>119```120121```php122// AppServiceProvider::boot() — makes N+1 and typos fail the suite123Model::shouldBeStrict(! $this->app->isProduction());124```125126SQLite differs from MySQL and Postgres on JSON operators, full-text search, locking and strict-mode errors. Run the integration suite against the production engine in CI even when local runs use SQLite.127128## Reference Material129130- `references/test-templates.md` — copy-paste starting points for each layer131- `references/checklist.md` — pre-merge self-check for test coverage132133## How to Use134135Load in this order and stop when the answer is clear:1361371. This file — the Quick Reference names every rule, and usually settles the question.1382. One rule file for the reasoning and both examples (~465 tokens each):139140```141rules/fake-repository-anonymous-class.md142rules/db-assert-inclusion-and-exclusion.md143```1441453. A `references/` file only when a rule points at one.146147`AGENTS.md` is every rule compiled into one document (~8k tokens), for agents that read the AGENTS.md convention. Do not load it when the individual rule files are reachable.148149## Related Skills150151- `laravel-engineering` — decide which changed boundary needs proof and keep docs current152- `laravel-patterns` — the layers these tests are organized around153- `laravel-eloquent` — the query rules the database tests assert154- `laravel-rest-api` — the endpoints the feature tests cover155- `laravel-async` — testing idempotency, batches and cache invalidation