Back to Course |
Testing in Laravel 11 For Beginners

Pest Architecture Testing

While debugging your Laravel application, you often use functions like dd(), dump(), etc. Architecture testing in Pest may help you scan the code before pushing to the repository, to ensure these functions don't exist anymore.

This is just one use-case. The architecture plugin allows you to check, for example, that only Enum files are in the specified folders.

Let's take a look at a practical example.

First, let's create a test.

php artisan make:test ArchTest

Let's check for debugging calls.

tests/Feature/ArchTest.php:

arch('No debugging calls are used')
->expect(['dd', 'dump'])
->not->toBeUsed();

If any debugging calls are left, we will see an error message.

We can check that in the specified folder, all classes extend only the specified class.

tests/Feature/ArchTest.php:

arch('No debugging calls are used')
->expect(['dd', 'dump'])
->not->toBeUsed();
 
arch('Models extend Eloquent Model')
->expect('App\Models')
->toExtend('Illuminate\Database\Eloquent\Model');


Pest 3: Architecture Presets

With pest v3 architecture testing, presets were introduced. Presets are a set of predefined architectural rules that you can use to test your application's architecture. These presets are designed to help you start architecture testing quickly and easily. There are five predefined presets: PHP, security, laravel, strict, and relaxed. For each preset to see the rules, it is best to look at their source in the GitHub.

For example, the laravel preset will check if your controllers only have index, show, create, store, edit, update, destroy methods and controllers class name have a suffix of Controller.

tests/Feature/ArchTest.php:

arch()->preset()->laravel();

I have a method download() in the controller that isn't in the allowed methods list, so the test would fail.

After removing this method, the test is passed.

If you still need the controller method, you can tell Pest to ignore it.

class ProductController extends Controller
{
// Other methods like index, create, etc...
 
// @pest-arch-ignore-next-line
public function download(): BinaryFileResponse
{
return response()->download(storage_path('files/product-specification.pdf'));
}
}

There is also a // @pest-arch-ignore-line to ignore only the exact line.


You can find more about architecture testing methods, presets, and use cases in the official documentation. Also, for more examples, you can check the Laravel News article Pest Architecture Plugin.