Custom helpers

Overview

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.

Creating custom helpers can improve readability and reduce the amount of code in your test suite.

Usage

By default, Pest autoloads the tests/Pest.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 helper:

1<?php // tests/Pest.php
2 
3/**
4 * Set the currently logged in user for the application.
5 *
6 * @return TestCase
7 */
8function actingAs(Authenticatable $user, string $driver = null)
9{
10 return test()->actingAs($user, $driver);
11}

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:

1<?php
2 
3it('redirects to user profile', function () {
4 $user = User::factory()->create();
5 
6 actingAs($user)->get('/profile')->assertSee($user->name);
7});

TIP: You can use custom helpers in higher order tests as if the helper was in the current test case.


Next section: IDE Plugins →