Custom Helpers

If you're transitioning to a functional approach for writing tests, you may wonder where to put your helpers that used to be protected or private methods in your test classes. When using Pest, these helper methods should be converted to simple functions.

For example, if your helper is specific to a certain test file, you may create the helper in the test file directly. Within your helper, you may invoke the test() function to access the test class instance that would normally be available via $this.

1use App\Models\User;
2use Tests\TestCase;
3 
4function asAdmin(): TestCase
5{
6 $user = User::factory()->create([
7 'admin' => true,
8 ]);
9 
10 return test()->actingAs($user);
11}
12 
13it('can manage users', function () {
14 asAdmin()->get('/users')->assertOk();
15})

Note: If your helper creates a custom expectation, you should write a dedicated custom expectation instead.

If your test helpers are utilized throughout your test suite, you may define them within the tests/Pest.php or tests/Helpers.php files. Alternatively, you can create a tests/Helpers directory to house your own helper files. All of these options will be automatically loaded by Pest.

1use App\Clients\PaymentClient;
2use Mockery;
3 
4// tests/Pest.php or tests/Helpers.php
5function mockPayments(): object
6{
7 $client = Mockery::mock(PaymentClient::class);
8 
9 //
10 
11 return $client;
12}
13 
14// tests/Feature/PaymentsTest.php
15it('may buy a book', function () {
16 $client = mockPayments();
17 
18 //
19})

As an alternative to defining helper methods as functions, you may define protected methods in your base test class and subsequently access them in your test cases using the $this variable.

1use App\Clients\PaymentClient;
2use PHPUnit\Framework\TestCase as BaseTestCase;
3use Mockery;
4 
5// tests/TestCase.php
6class TestCase extends BaseTestCase
7{
8 protected function mockPayments(): void
9 {
10 $client = Mockery::mock(PaymentClient::class);
11 
12 //
13 
14 return $client;
15 }
16}
17 
18// tests/Pest.php
19pest()->extend(TestCase::class)->in('Feature');
20 
21// tests/Feature/PaymentsTest.php
22it('may buy a book', function () {
23 $client = $this->mockPayments();
24 
25 //
26})

In this section, we explored creating custom helpers. Digging deeper, you may even want to generate a custom expectation. Let's jump into that topic in the next chapter: Custom Expectations