Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 67 ยท Testing

Testing with Pest

Learn to test Laravel apps with Pest - feature and unit tests, artisan test, expectations, datasets and hooks, plus a tiny runnable Pest-style test runner.

Laravel was built with testing in mind. A new project ships with a tests folder, a phpunit.xml file and an artisan test command. Since Laravel 11, new projects can choose between Pest and PHPUnit, and this project uses Pest. Pest runs on top of PHPUnit, so everything you learn about assertions, test doubles and database testing applies to both.

In this lesson you will see the shape of a Pest test, the difference between feature and unit tests, how expectations and datasets work, and how to run tests from the command line. The real Pest code is read-only; the runnable examples build a tiny Pest-style runner in plain PHP so you can see how it(), expect() and datasets can work. For the general ideas behind testing, read Testing PHP Code first.

Pest or PHPUnit?

Both frameworks run the same engine. The difference is style. A PHPUnit test is a method on a class:

PHP
class PriceTest extends TestCase
{
    public function test_discount_is_applied(): void
    {
        $this->assertSame(1875, applyDiscount(2500, 25));
    }
}

The same test in Pest is a function call with a readable sentence:

PHP
it('applies a percentage discount', function () {
    expect(applyDiscount(2500, 25))->toBe(1875);
});

Pest tests have less ceremony, read like documentation and chain expectations fluently. PHPUnit is more traditional and what most older Laravel code uses. You can mix both in one project, so adopting Pest never forces a rewrite.

Feature tests and unit tests

A fresh Laravel project has two folders:

TEXT
tests/
  Feature/
    ExampleTest.php
  Unit/
    ExampleTest.php
  Pest.php
  TestCase.php
  • tests/Unit holds tests of single classes with no framework needs: a price calculator, a slug generator. They are the fastest and do not boot the application.
  • tests/Feature holds tests that boot Laravel and exercise several pieces together, usually by sending a simulated HTTP request to a route and checking the response or the database. Most Laravel tests are feature tests (see HTTP and Database Tests).

The file tests/Pest.php is where you tell Pest which folders use the Laravel TestCase:

PHP
pest()->extend(Tests\TestCase::class)
    ->in('Feature');

That one line is why $this->get('/') works inside a Feature test: the closure is bound to a TestCase instance that boots the app.

flowchart TD
    A["php artisan test"] --> B["Pest finds tests/**/*Test.php"]
    B --> C["Unit test: runs the closure directly"]
    B --> D["Feature test: boots Laravel via TestCase"]
    C --> E["Report: passed / failed"]
    D --> E

Both kinds of test end in the same report. Feature tests also boot the application first.

Writing and running tests

Create a test with Artisan. Pest is the default in this project:

Terminal
php artisan make:test --pest PriceTest          # tests/Feature/PriceTest.php
php artisan make:test --pest --unit PriceTest   # tests/Unit/PriceTest.php

Run them:

Terminal
php artisan test                  # everything
php artisan test --compact        # shorter output
php artisan test tests/Feature/PriceTest.php
php artisan test --filter="applies a percentage discount"
php artisan test --parallel       # several processes at once

php artisan test calls Pest (or PHPUnit) and prints a readable report. The command exits with a non-zero code when anything fails, which is what makes a CI job turn red.

Test names are plain sentences. it('...') prefixes the sentence with "it", and test('...') leaves it alone:

PHP
test('a guest is redirected to the login page', function () {
    $this->get('/dashboard')->assertRedirect('/login');
});

Expectations

Pest's expect() wraps a value and lets you chain checks. A few you will use all the time:

PHP
expect($total)->toBe(1875);              // strict ===
expect($name)->toEqual('Ada');            // loose ==
expect($list)->toHaveCount(3);
expect($user->email)->toContain('@');
expect($value)->toBeNull();
expect($flag)->toBeTrue();
expect(fn () => divide(1, 0))->toThrow(DivisionByZeroError::class);
expect($posts)->each->toBeInstanceOf(Post::class);

Prefer toBe() over toEqual(): strict comparison catches the integer-versus-string bugs that loose comparison hides. Chaining with and() checks several values in one test:

PHP
expect($order->total)->toBe(5000)
    ->and($order->status)->toBe('paid');

Building a tiny Pest-style runner

Pest's trick is that it() just stores a closure, and expect() returns an object whose methods throw when a check fails. Here is the whole idea in plain PHP. This is a stand-in, not Pest's real code, which also handles hooks, plugins, parallel runs and nicer diffs.

PHP A mini it() and expect()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last test fails on purpose so you can read a failure message. Because toBe() returns the expectation, chaining is just method calls returning objects. Pest's real implementation adds a lot on top, but this is the core of why the syntax feels so light.

Datasets: one test, many inputs

Writing five nearly identical tests is wasteful. Pest datasets run one test closure once per row of data and name each run, so a failure points at the exact input:

PHP
it('validates usernames', function (string $name, bool $valid) {
    expect(isValidUsername($name))->toBe($valid);
})->with([
    'too short'   => ['ab', false],
    'just right'  => ['ada_lovelace', true],
    'has a space' => ['ada lovelace', false],
]);

PHPUnit calls the same idea a data provider. Here is a stand-in that loops over a named dataset and reports each case:

PHP A dataset runner

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

You can also keep shared datasets in tests/Datasets and reuse them by name with ->with('usernames').

Setup and teardown hooks

Repeated setup belongs in a hook. Pest offers beforeEach(), afterEach(), beforeAll() and afterAll(), and Feature tests can use traits such as RefreshDatabase (covered in the next lesson):

PHP
beforeEach(function () {
    $this->basket = new Basket();
});

it('starts empty', function () {
    expect($this->basket->items())->toBeEmpty();
});

Inside a test, $this is the test case, so values set in beforeEach() are available on it.

Name tests after behavior, not methods: "it rejects expired coupons" tells you what broke; "test coupon 3" does not. Keep each test about one idea, and keep unit tests free of the database so they stay fast.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which command runs a single Pest test file in a Laravel project?

    php artisan test accepts a file path (or --filter for a name) and runs only those tests.
  2. 2. What is the main difference between a Feature test and a Unit test in Laravel?

    Feature tests extend the Laravel TestCase and boot the app, usually sending a simulated HTTP request. Unit tests check one class without the framework.
  3. 3. Why is toBe() generally preferred over toEqual()?

    toBe() uses ===. Loose comparison can hide type bugs, so strict is the safer default.
  4. 4. What does a Pest dataset do?

    A dataset passes each row to the test closure as arguments and reports every run separately, like a PHPUnit data provider.

Summary

  • Pest is a friendlier syntax on top of PHPUnit; both run with php artisan test.
  • Unit tests check one class quickly; Feature tests boot Laravel and exercise requests, the database and more.
  • expect($value)->toBe(...) chains readable checks, and toBe() is strict.
  • Datasets run one closure for many inputs; beforeEach() removes repeated setup.
  • The runnable examples here are plain-PHP stand-ins that show how it(), expect() and datasets can work.

Next: HTTP and Database Tests