Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

FvsJson's avatar

Pest unit test seed before all from the pest.php file

Hi all so there are two seeds that wi would like to run before all my fe3ature test but when i try and set it up it says there is not $this object

so the below code seems to work but i would just like to run the seed once before all test to reduce testing time

uses(Tests\TestCase::class)->beforeEach(function () {
    $this->seed(RoleSeeder::class);
    $this->seed(PermissionSeeder::class);
})->in('Feature', 'Unit');
0 likes
3 replies
Batman55's avatar

Anyone struggling with this, here is what I did:

In Pest.php

	use Database\Seeders\RoleSeeder;

    pest()->extend(Tests\TestCase::class)
    ->use(Illuminate\Foundation\Testing\LazilyRefreshDatabase::class)
    ->in('Feature')
    ->beforeEach(function () {
            $this->seed(RoleSeeder::class);
        })
    ->in('Feature', 'Unit');

This runs the Role seeder anytime the database is refreshed for a test.

newbie360's avatar

@Batman55 But not all Tests require the roles database data..., it may take very long when you run a full test

Batman55's avatar

@newbie360 That is true. This is trying to solve a specific problem, making sure certain data is always in the database for tests.

In the OP's case, they want roles and permissions available for every test. In my specific case, all users have a role (user model is dependent on roles) and must be logged into the application to do anything. Thus, the Roles must be available to almost all tests.

Very few tests do not require this in place, so the performance hit for those few is well worth the current set up costs.

Please or to participate in this conversation.