Back to Course |
Testing in Laravel 9 For Beginners: PHPUnit, Pest, TDD

What is PEST? How It Works: Simple Example

So far, we have been launching tests with the php artisan test, which runs the tests with PHPUnit under the hood. There is another approach, which became very popular in 2021-2022, called Pest. It is a PHP testing framework and not Laravel-specific. It also uses PHPUnit under the hood but with a different, shorter syntax.

Let's rewrite the test_unauthenticated_user_cannot_access_product, which is in AuthTest from PHPUnit to a Pest.


Install Pest

When creating a new Laravel project, you can use Pest as a testing framework. Also, for example, when installing Breeze or Jetstream, you can choose to use tests with Pest.

But here, we will install Pest manually.

composer require pestphp/pest --dev --with-all-dependencies
./vendor/bin/pest --init

To run tests you can use command ./vendor/bin/pest or stick with a php artisan test. Both commands will run full tests sweet.


Pest Test

Now, let's create a Pest test. Laravel has a flag for creating a new test to create it as a Pest test.

php artisan make:test AuthenticationTest --pest

If we take a look at the generated test it is very similar to the example test but shorter.

tests/Feature/AuthenticationTest.php:

test('example', function () {
$response = $this->get('/');
 
$response->assertStatus(200);
});

Looking at the syntax, there's no class, no use statements, and no methods. It's just a test with a name and a callback function. Now, let's rewrite that test.

tests/Feature/AuthenticationTest.php:

test('unauthenticated user cannot access products', function () {
$response = $this->get('/products');
 
$response->assertStatus(302);
$response->assertRedirect('login');
});

Or we can make it shorter by chaining methods.

tests/Feature/AuthenticationTest.php:

test('unauthenticated user cannot access products', function () {
$this->get('/products')
->assertStatus(302)
->assertRedirect('login');
});

But Pest can make it even shorter. If you have a test with one sentence, like in this case, you can ditch a callback and use Higher Order Testing.

tests/Feature/AuthenticationTest.php:

test('unauthenticated user cannot access products')
->get('/products')
->assertStatus(302)
->assertRedirect('login');

first pest test


Commit for this lesson