Pest PHP in an Existing Suite: Setup, Syntax, and CI
Pest PHP runs on top of PHPUnit, so you can add it to an existing suite without rewriting your tests. Install the runner through Composer and run your current TestCase classes with ./vendor/bin/pest. You can then write new tests with Pest's closure syntax alongside the classes you already have.
In a large PHP codebase, the setup around a test can get in the way of writing it. PHPUnit tests need class declarations, repeated boilerplate methods, and lengthy assertion calls. That repetition can discourage developers from adding small, focused unit tests. Pest reduces the boilerplate with test() and it() functions, chainable expect() assertions, and inline datasets.
Why Adopt Pest Without Rewriting PHPUnit
A production suite may have hundreds or thousands of tests that depend on custom assertions, framework fixtures, and database transactions. Converting all of them at once is risky. It also holds up feature work while the team deals with merge conflicts and reviews the converted tests.
Pest wraps and extends PHPUnit. Classes extending PHPUnit\Framework\TestCase keep their assertions, lifecycle hooks, and mock objects. Use Pest syntax for new tests, and convert older test classes when you next need to change them.
This gradual approach also works for static analysis: PHPStan lets you enforce strict rules on new code while keeping older issues in a baseline. Greg Beaver's article on testing with PHPT and xUnit makes a related point about test architecture. Teams are more likely to maintain tests that are fast and pleasant to write.
Step 1: Installing Pest with Composer
For the current Pest 5 release, check that your project and CI can run PHP 8.4 or newer. Pest 5 uses PHPUnit 13, so review your existing PHPUnit constraints and extensions before changing the lockfile. If your application still targets an older PHP release, choose a compatible Pest major version using that version's documentation instead of copying the commands below.
The current Pest installation guide removes a direct phpunit/phpunit requirement first, then adds Pest as a development dependency. This changes Composer dependencies, not your PHPUnit test files. Check the resulting composer.json and composer.lock in your pull request:
composer remove phpunit/phpunit --dev
composer require pestphp/pest --dev --with-all-dependencies
Keep test frameworks in require-dev so production installs can omit them with composer install --no-dev, as covered in Composer dependency management.
Once Composer completes the download, run the initialization command:
./vendor/bin/pest --init
The command creates tests/Pest.php, Pest's bootstrap file. Use it to define shared test cases, bind traits, and register custom expectation helpers.
Verify your setup by running the Pest executable against your existing tests:
./vendor/bin/pest
Pest runs PHPUnit class tests alongside Pest closure tests, using your phpunit.xml configuration. Check the complete run for failures and compare its test count with your previous runner before changing CI.
Step 2: Configuring PHPUnit Interoperability in Pest.php
By default, Pest runs test closures in the context of PHPUnit\Framework\TestCase. If your project has a custom base test case, such as a web framework's Tests\TestCase, bind it to the relevant test directories in tests/Pest.php.
Open tests/Pest.php and use the current pest()->extend() API for folders whose closure tests need your application base class:
<?php
pest()->extend(Tests\TestCase::class)->in('Feature');
This binds Tests\TestCase to Pest closure tests in tests/Feature/. Keep any existing PHPUnit classes as they are. If a separate folder needs a different base class or trait, add a binding for that folder.
Inside a Pest test closure in tests/Feature/, $this refers to an instance of Tests\TestCase. Your protected helper methods, setup properties, and mock creators are available through it:
it('retrieves user profile information', function () {
// $this refers to Tests\TestCase
$user = $this->createTestUser();
$response = $this->getJson("/api/users/{$user->id}");
expect($response->status())->toBe(200);
});
You can read more about binding classes and traits in the Pest test configuration documentation.
Step 3: Writing Tests with test(), it(), and expect()
Define a test with test() or it(). Both take a description and a closure. When printing results, it() puts the word "it" before the description, so write the name as a behavior that completes that sentence.
These tests use both forms:
<?php
test('tax rate defaults to standard percentage for local orders', function () {
$tax = calculateTax(subtotal: 100.0, country: 'US');
expect($tax)->toBe(7.0);
});
it('rejects negative currency amounts during calculation', function () {
expect(fn () => calculateTax(subtotal: -10.0, country: 'US'))
->toThrow(InvalidArgumentException::class);
});
You can learn more about lifecycle hooks and test execution in the standard Pest documentation.
Fluent Assertions with expect()
Use expect() in place of assertion calls such as $this->assertEquals() or $this->assertCount(). Read the expectation from left to right: the value comes first, followed by the checks. You can chain several checks on the same value.
Common checks look like this:
// Value equality and type checks
expect($order->status)->toBe('completed');
expect($order->total)->toBeFloat()->toBe(49.99);
// Collections and arrays
expect($order->items)
->toBeArray()
->toHaveCount(3)
->toContain($bookItem);
// Negation using the not modifier
expect($order->discount)
->not->toBeNull()
->not->toBe(0.0);
// String assertions
expect($user->email)
->toBeString()
->toStartWith('support@')
->toEndWith('.com');
When an expectation fails, Pest prints a diff showing the mismatched properties, expected types, and line numbers. See the Pest expectations documentation for the full list of methods.
Before and After: Converting a PHPUnit Test Case to Pest
To see the reduction in boilerplate, compare a traditional class-based PHPUnit test with its equivalent Pest implementation. Both examples test the same discount calculator logic and assert identical outcomes.
Before: Traditional PHPUnit Test Case
<?php
namespace Tests\Unit;
use App\Billing\DiscountCalculator;
use PHPUnit\Framework\TestCase;
class DiscountCalculatorTest extends TestCase
{
private DiscountCalculator $calculator;
protected function setUp(): void
{
parent::setUp();
$this->calculator = new DiscountCalculator();
}
public function test_it_applies_percentage_discount(): void
{
$total = $this->calculator->applyDiscount(subtotal: 100.0, discountPercent: 20);
$this->assertIsFloat($total);
$this->assertSame(80.0, $total);
}
public function test_it_returns_full_price_when_discount_is_zero(): void
{
$total = $this->calculator->applyDiscount(subtotal: 50.0, discountPercent: 0);
$this->assertSame(50.0, $total);
}
}
After: Equivalent Pest Implementation
<?php
use App\Billing\DiscountCalculator;
beforeEach(function () {
$this->calculator = new DiscountCalculator();
});
it('applies percentage discount', function () {
$total = $this->calculator->applyDiscount(subtotal: 100.0, discountPercent: 20);
expect($total)->toBeFloat()->toBe(80.0);
});
it('returns full price when discount is zero', function () {
$total = $this->calculator->applyDiscount(subtotal: 50.0, discountPercent: 0);
expect($total)->toBe(50.0);
});
The Pest version drops class declarations, namespace nesting, visibility keywords, return type declarations on test methods, and parent setup calls. The test logic and asserted values remain identical.

Step 4: Streamlining Parameterized Tests with Datasets
In PHPUnit, you run an assertion against multiple inputs with a data provider method annotated with @dataProvider or #[DataProvider]. The inputs live apart from the test method, so you have to move between them when reading the test. Pest's with() method lets you put a dataset beside the assertion.
Inline Datasets
For simple scalar inputs, pass an array directly to with():
it('accepts valid email domains', function (string $email) {
expect(isValidDomain($email))->toBeTrue();
})->with([
'admin@example.com',
'editor@company.org',
'billing@platform.net',
]);
Named Datasets with Multiple Arguments
When testing functions with multiple inputs and expected outputs, use associative arrays with descriptive keys:
it('calculates shipping costs across geographic zones', function (float $weight, string $zone, float $expectedCost) {
$rate = calculateShipping(weight: $weight, zone: $zone);
expect($rate)->toBe($expectedCost);
})->with([
'local lightweight parcel' => [1.5, 'domestic', 5.00],
'local heavy freight' => [25.0, 'domestic', 22.50],
'international express' => [2.0, 'international', 35.00],
]);
If a case fails, Pest prints its descriptive key in the terminal. You can identify the failing scenario by name rather than looking up a row index.
Reusable Datasets
If multiple test files share the same dataset, declare it globally in tests/Datasets/ using the dataset() function:
// tests/Datasets/Currencies.php
dataset('supported_currencies', [
'US Dollar' => ['USD', '$'],
'Euro' => ['EUR', '€'],
'British Pound' => ['GBP', '£'],
]);
Reference the dataset by name in any test file:
it('formats monetary values correctly', function (string $code, string $symbol) {
expect(formatCurrency(amount: 10.0, currency: $code))->toContain($symbol);
})->with('supported_currencies');
You can also combine datasets or build them dynamically with generator functions. The Pest datasets documentation has complete examples.

Step 5: Configuring Continuous Integration
Run Pest in continuous integration to check pull requests before merging. Pass --ci so Pest ignores any ->only() focus left on a test and runs the full suite. The Pest CLI reference documents this behavior; the flag does not fail merely because ->only() is present.
Add a GitHub Actions workflow in .github/workflows/tests.yml:
name: Automated Tests
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main, develop ]
jobs:
pest-tests:
name: Pest Test Suite
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Set up PHP runtime
uses: shivammathur/setup-php@v2
with:
php-version: '8.4'
coverage: none
tools: composer:v2
- name: Get Composer cache directory
id: composer-cache
run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT
- name: Cache Composer dependencies
uses: actions/cache@v4
with:
path: ${{ steps.composer-cache.outputs.dir }}
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
restore-keys: ${{ runner.os }}-composer-
- name: Install dependencies
run: composer install --prefer-dist --no-progress --no-interaction
- name: Run Pest test suite
run: ./vendor/bin/pest --ci --bail
Useful Command Line Options for CI
These flags control how the CI run executes and when it fails:
--ci: Ignores->only()focus and runs the full suite.--bail: Stops at the first failure to save runner minutes on a broken build.--parallel(or-p): Runs tests across available CPU cores to reduce execution time on multi-core runners.--coverage --min=80: Measures code coverage and fails the build if total coverage falls below the specified percentage.
Common Mistakes to Avoid
- Rewriting the entire existing test suite on day one: A bulk conversion can introduce false positives or lose custom assertions. Keep existing PHPUnit tests in place and write new tests with Pest.
- Leaving
->only()flags committed in code: To debug a single test locally, developers often append->only()totest()orit(). Use--ciso a focused run cannot hide failures elsewhere in the suite. - Forgetting to register base classes in
tests/Pest.php: If your tests rely on database migrations, factory traits, or application bootstrap methods, calling$this->actingAs()or$this->get()inside a Pest closure fails unless you configureuses(TestCase::class)->in('Feature'). - Calling PHPUnit and Pest binaries inconsistently: Having some developers run
vendor/bin/phpunitwhile others runvendor/bin/pestleads to divergent test configurations. Set the test script incomposer.jsonby mapping"test": "pest"so everyone runs the same binary.

Frequently Asked Questions
Can I run both PHPUnit and Pest tests in the same repository?
Yes. When you run ./vendor/bin/pest, it inspects all files ending in Test.php in the suite's directory structure. It runs PHPUnit classes through PHPUnit's internal engine and Pest closure tests through its functional runner.
Does Pest respect existing phpunit.xml settings?
Yes. Pest reads your project's phpunit.xml or phpunit.xml.dist. Your test suite definitions, directory locations, environment variables, coverage filters, and database connection settings still apply.
Can I convert existing PHPUnit tests automatically?
Yes. The Pest team maintains Drift, an automated conversion tool. Install it with composer require pestphp/pest-plugin-drift --dev and run ./vendor/bin/pest --drift. The plugin parses class-based PHPUnit tests and rewrites them into Pest functional syntax. For details, see the Pest Drift plugin repository.
How does Pest handle test lifecycle hooks?
Pest's lifecycle functions correspond to PHPUnit's setUp and tearDown methods. Use beforeEach() to initialize state before each test in the file, and afterEach() to clean up resources afterward. For suite-level initialization, use beforeAll() and afterAll(). These functions accept closures and run in place of class-based setup methods.