09 January 2024
Sebastian
Sniffing out stray ray() calls with Pest architecture testing
Whether you're building a shiny new feature or refactoring bug deep in a legacy codebase, before you merge your work to production you want to get rid of all those ray()
calls you littered the codebase with. You'll probably get rid of most of them on time, but every now and then a stray call gets forgotten during code review.
If you're using Pest—a PHP testing framework—you can ensure not a single ray()
call gets merged by sniffing them out with an architecture test.
Pest's architecture tests allow you to specify a set of rules for your application's architecture.
For example, here's a test that ensures the App\Models
namespace only contain models. If the namespace includes a class that doesn't extend Illuminate\Database\Eloquent\Model
, it will fail.
arch('app')
->expect('App\Models')
->toExtend('Illuminate\Database\Eloquent\Model');
Architecture testing and Ray
Architecture tests can also assert that a function is never used. In our case, avoiding any ray()
call in the codebase.
First, add Pest to your project. (Follow the installation guide for more in-depth instructions.)
composer require pestphp/pest --dev --with-all-dependencies
./vendor/bin/pest --init
Then, define your architecture test in tests/ArchTest.php
.
arch('it will not use ray')
->expect('ray')
->not->toBeUsed();
This test will fail when ray
appears in your codebase. While we're here, we can extend this to fail when we use any debugging function.
arch('it will not use debugging functions')
->expect(['dd', 'dump', 'ray'])
->each->not->toBeUsed();
During development, you'll want to use debugging functions without Pest nagging about them. To opt out of the architecture test, use the --exclude-arch
tag when running tests.
Now, you can exclude the arch
group when running Pest during development.
./vendor/bin/pest --exclude-arch
Happy testing!
Understand and fix bugs faster
Ray is a desktop application that serves as the dedicated home for debugging output. Send, format and filter debug information from both local projects and remote servers.