How a Five Line Architecture Test Caught a Data Leak a Code Review Missed
TL;DR: Pest PHP can test the structure of your code, not just its behavior. Write your team rules as architecture tests and CI enforces them on every commit. One such test caught a multi-tenant data leak that a human review had missed. We had a rule. Every model holding tenant-specific data must use our BelongsToTenant trait. That trait adds the global scope that keeps one clinic from seeing another clinic's data. The rule was in onboarding. It was in the code review checklist. Everyone knew it. A developer joined the team. Three weeks in they added a new model and forgot the trait. The reviewer was focused on the business logic, which was genuinely well written, and did not notice the missing trait. The model shipped. For two days one clinic could see fragments of another clinic's data in one specific report. A support ticket caught it. Our tests did not. That was the day architecture tests went into the project. What an Architecture Test Is Most tests check behavior. Given this input the function returns that output. An architecture test checks structure instead. It asserts things about how the code is organized rather than what it computes. Pest has an arch function for exactly this. // tests/Architecture/ArchTest.php arch ( 'tenant models must use the BelongsToTenant trait' ) -> expect ( 'App\Models' ) -> toUseTrait ( 'App\Traits\BelongsToTenant' ) -> ignoring ( 'App\Models\SystemSetting' ); arch ( 'controllers may not touch the DB facade directly' ) -> expect ( 'App\Http\Controllers' ) -> not -> toUse ( 'Illuminate\Support\Facades\DB' ); arch ( 'services may not depend on the HTTP request' ) -> expect ( 'App\Services' ) -> not -> toUse ( 'Illuminate\Http\Request' ); arch ( 'no env calls outside config files' ) -> expect ( 'App' ) -> not -> toUse ( 'env' ); These run in CI on every commit. Break a rule and the build fails with a message naming the rule and the file that broke it. The Tests That Earned Their Keep The tenant trait test caught four more models over