My app uses the spatie/laravel-permission package to manage roles and permissions, and PestPHP for testing.
It’s normal to set up users, roles, and permissions for each test. I created SetupRoles
trait to accomodate this.
Normally, we would do this manually in each test file:
However, we would prefer to automatically run setUpRoles()
for each test, similar to how the RefreshDatabase
trait works.
To achieve this, we need to extend setUpTraits
in our tests/TestCase
like so:
Essentially, this scans all used classes from the test file. If SetUpRoles
trait is detected, it calls the setUpRoles
method.
Above is how RefreshDatabase
is called automatically from our test.
Finally, we just need to register our trait inside tests/Pest.php
like this:
Done. Now, you don’t need to reference the traits in your test files anymore.