Skip to content

Latest commit

 

History

History
89 lines (64 loc) · 2.63 KB

File metadata and controls

89 lines (64 loc) · 2.63 KB
title Custom Helpers
description When transitioning to a functional approach for writing tests, you may convert the helpers that used to be protected or private methods in your test classes into simple functions.

Custom Helpers

If you are transitioning to a functional approach for writing tests, you may wonder where to place the 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 that 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:

use App\Models\User;
use Tests\TestCase;

function asAdmin(): TestCase
{
    $user = User::factory()->create([
        'admin' => true,
    ]);

    return test()->actingAs($user);
}

it('can manage users', function () {
    asAdmin()->get('/users')->assertOk();
})

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

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

use App\Clients\PaymentClient;
use Mockery;

// tests/Pest.php or tests/Helpers.php
function mockPayments(): object
{
    $client = Mockery::mock(PaymentClient::class);

    //

    return $client;
}

// tests/Feature/PaymentsTest.php
it('may buy a book', function () {
    $client = mockPayments();

    //
})

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

use App\Clients\PaymentClient;
use PHPUnit\Framework\TestCase as BaseTestCase;
use Mockery;

// tests/TestCase.php
class TestCase extends BaseTestCase
{
    protected function mockPayments(): void
    {
        $client = Mockery::mock(PaymentClient::class);

        //

        return $client;
    }
}

// tests/Pest.php
pest()->extend(TestCase::class)->in('Feature');

// tests/Feature/PaymentsTest.php
it('may buy a book', function () {
    $client = $this->mockPayments();

    //
})

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