Writing helpers in Pest

Writing helpers in Pest

In case you didn't notice, Pest beta is now available! Check the website to get started:

Pest - An elegant PHP Testing Framework
Introducing Pest: An elegant PHP Testing Framework with a focus on simplicity

In this article, we are going to check how can you write custom helpers to improve readability and reduce the amount of code of your test suite.

While Pest is very powerful out-of-the-box, you may have some testing code specific to your project that you don't want to repeat in every test.

tests/Helpers.php


By default, Pest autoloads the tests/Helpers.php file. In this file, you can place your custom helpers. Of course, if those helpers are specific to a test file, you can place them inside of that test file only.

For example, imagine that you want to make a custom helper for the actingAs() Laravel Framework helper:

<?php // tests/Helpers.php

use Tests\TestCase;
use Illuminate\Contracts\Auth\Authenticatable;

/**
 * Set the currently logged in user for the application.
 */
function actingAs(Authenticatable $user, string $driver = null): TestCase
{
    return test()->actingAs($user, $driver);
}
TIP: use the test function without any arguments to get access to the current test case.

Now, you can use the actingAs helper in your tests:

<?php // tests

it('redirects to user profile', function () {
    $user = factory(User::class)->create();

    actingAs($user)->get('/profile')->assertSee($user->name);
});

If you are not using Pest yet, now is a great time to get started: pestphp.com 🔥

Show Comments