Testing
SlidesThis page shows how to set up a plain PHP project for Test Driven Development (TDD) with Pest, and how to grow a small function test-first.
After finishing this page you will
- understand the Red – Green – Refactor cycle of TDD
- be able to set up a plain PHP project with Composer autoloading and Pest
- write tests with Pest’s
test()andexpect() - run the test suite from the command line
- build a function step by step, one test at a time
Test Driven Development
Section titled “Test Driven Development”In Test Driven Development you write the test first, before the code it tests. You work in small steps, and each step is one turn of a three-part cycle:
- Red — write a test for a tiny piece of behaviour that does not exist yet. Run it. It fails. (Of course — you haven’t written the code.)
- Green — write the simplest code that makes the test pass. Nothing more.
- Refactor — clean up the code now that a passing test protects you from breaking it.
Then you start again at Red with the next piece of behaviour.
The example we build here lives in wordplay-php. We write one class
src/Wordplay.php with a function isPalindrome, and grow it test-first.
A palindrome is a word that reads the same forwards and backwards, like oxo
or anna.
Setting up the Project
Section titled “Setting up the Project”We start the project as usual with composer init. For the example code here we will be using the namespace Designpatterns
and project name Wordplay.
Installing Pest
Section titled “Installing Pest”Pest is a testing framework built on top of PHPUnit. It is a dev dependency:
you need it while developing, but not on the production server. So we install it
with --dev:
$ composer require pestphp/pest --dev --with-all-dependenciesThis adds Pest (and PHPUnit, which it builds on) under require-dev in
composer.json, and downloads them into vendor/.
now we have an executable file ./vendor/bin/pest.
Initialising Pest
Section titled “Initialising Pest”We can use the pest exsecutable as a generator that sets up the test folder:
$ ./vendor/bin/pest --initIt creates three files:
phpunit.xml— configuration: where the tests are, which folders to measuretests/Pest.php— shared setup for all tests (custom expectations live here)tests/TestCase.php— the base class your tests can extend
We need to add the information about the tests/ folder to composer.json:
"autoload-dev": { "psr-4": { "Tests\\": "tests/" }},After adding this you need to run
composer dump-autoloadThe you can run the dummy tests with
./vendor/bin/pestAdding a script to composer.json
Section titled “Adding a script to composer.json”Typing ./vendor/bin/pest every time is tedious, so we add
a script to composer.json:
"scripts": { "test": "pest"}Now composer test runs the whole suite. Run it once to check the setup, you should see the sample tests pass:
$ composer run test> pest
PASS Tests\Feature\ExampleTest✓ example
PASS Tests\Unit\ExampleTest✓ example
Tests: 2 passed (2 assertions)Duration: 0.05sThe First Test (Red)
Section titled “The First Test (Red)”In TDD the test comes first. Create tests/Unit/WordplayTest.php and describe
the smallest thing a palindrome checker should do: a single letter is a
palindrome.
<?php
use Designpatterns\Wordplay;
test('palindrome', function () { // Arrange: $wordplay = new Wordplay(); // Act: $result = $wordplay->isPalindrome('x'); // Assert: expect($result)->toBeTrue();});You can see the usual structure of a test: Arrange = create the objects we need. Act = call the method under test. Assert = check the return value.
Two pieces specific to Pest here:
test('name', function () { … })registers a test with a readable name.expect($value)->toBeTrue()is an expectation. Pest has many:toBe,toEqual,toBeTrue,toBeFalse,toContain, and more. See Expectations in the pest docu.
Run it:
$ composer run test
FAIL Tests\Unit\WordplayTest ⨯ palindrome
Error: Class "Designpatterns\Wordplay" not found at tests/Unit/WordplayTest.php:6Red, as expected: the class does not exist yet.
Make it Green
Section titled “Make it Green”Write the simplest code that makes the test pass. The test only checks one
word, 'x', and expects true — so returning true is enough for now:
<?php
declare(strict_types=1);
namespace Designpatterns;
class Wordplay {
public function isPalindrome(string $word): bool { return true; }}Because we added a new file to an already-mapped namespace, Composer finds it —
but the very first time you set up autoloading (or change the autoload section)
you must rebuild the autoloader once:
$ composer dump-autoloadRun the tests again:
$ composer test> pest
PASS Tests\Feature\ExampleTest✓ example
PASS Tests\Unit\ExampleTest✓ example
PASS Tests\Unit\WordplayTest✓ palindrome
Tests: 3 passed (3 assertions)Duration: 0.06sGreen. Yes, return true is obviously wrong — but it passes every test we have
written so far. In TDD that is exactly the point: the next test will force us
to write real code.
A Second Case (Red again)
Section titled “A Second Case (Red again)”Add a word that is not a palindrome. Back in WordplayTest.php:
test('palindrome', function () { $wordplay = new Wordplay(); expect($wordplay->isPalindrome('x'))->toBeTrue(); expect($wordplay->isPalindrome('nix'))->toBeFalse();});$ composer test
FAIL Tests\Unit\WordplayTest ⨯ palindrome
Failed asserting that true is false. at tests/Unit/WordplayTest.php:6Red again: isPalindrome('nix') returns true, but we expect false.
A Naive Implementation
Section titled “A Naive Implementation”What is the simplest rule that passes both cases? 'x' is short, 'nix' is
longer — so we could just look at the length:
public function isPalindrome(string $word): bool { $len = strlen($word); if ($len < 2) { return true; } return false; }$ composer test
PASS Tests\Unit\WordplayTest ✓ palindromeGreen — both cases pass. But this code does not check palindromes at all, it only checks the length. We know it is wrong. The way to prove it in TDD is to write a test that exposes the lie.
A Case that Breaks it (Red)
Section titled “A Case that Breaks it (Red)”Add a real palindrome that is longer than one letter:
test('palindrome', function () { $wordplay = new Wordplay(); expect($wordplay->isPalindrome('x'))->toBeTrue(); expect($wordplay->isPalindrome('nix'))->toBeFalse(); expect($wordplay->isPalindrome('oxo'))->toBeTrue();});$ composer test
FAIL Tests\Unit\WordplayTest ⨯ palindrome
Failed asserting that false is true. at tests/Unit/WordplayTest.php:7'oxo' has length 3, so the naive code returns false — but oxo is a
palindrome. Now we are forced to implement the real thing.
The Real Implementation (Green)
Section titled “The Real Implementation (Green)”A word is a palindrome if it is equal to itself reversed. We split the word into characters, reverse the list, and compare:
public function isPalindrome(string $word): bool { $letters = mb_str_split($word); $reversed = array_reverse($letters); return $letters === $reversed; }$ composer test
PASS Tests\Unit\WordplayTest ✓ palindrome
Tests: 1 passed (3 assertions)Green, and this time for the right reason.
Why mb_str_split and not the shorter strrev($word)? strrev works on
bytes, not characters. For plain ASCII like oxo both would work, but a word
with an umlaut such as öl stores that ö as two bytes, and strrev would tear
those bytes apart and produce garbage. mb_str_split keeps each character whole —
the same reason the rest of this project uses it.
Refactor
Section titled “Refactor”With three passing assertions guarding us, we could now clean up the code without fear — rename variables, extract a helper, simplify. Here the function is already small, so there is nothing to do. But this is the step where, on bigger code, you improve the design because the tests tell you immediately if you break something.
That is the whole loop again:
- Red —
expect(...)->toBeTrue()for behaviour that doesn’t exist - Green — the simplest code that passes
- Refactor — tidy up under the protection of the tests
The finished test file and class match the example in wordplay-php. From here
you can add the next behaviour the same way — the example project goes on to
countLetters and anagramPairs, each grown test-first (and those use the ds
extension, so the full composer.json also requires ext-ds).
Running the tests
Section titled “Running the tests”A few ways to run the suite while you work:
$ composer test # via the script in composer.json$ ./vendor/bin/pest # the runner directly$ ./vendor/bin/pest tests/Unit/WordplayTest.php # a single fileKeep the tests running as you code — in TDD you should rarely be more than one failing test away from your last green state.
Final Quiz
Section titled “Final Quiz”In the Red–Green–Refactor cycle, what do you do first for a new piece of behaviour?
- Write a failing test for it
- Write the implementation, then a test
- Refactor the existing code
- Run
composer dump-autoload
You are in the “Green” step. What code should you write?
- The full, final implementation with all edge cases
- The simplest code that makes the current tests pass
- Only comments describing what to do later
- A second test
Why is Pest installed with composer require pestphp/pest --dev?
- It is only needed during development, not on the production server
-
--devmakes the download faster - Without
--devPest cannot find your tests - It installs Pest globally instead of into
vendor/
With the PSR-4 mapping "Designpatterns\\": "src/", where must the class Designpatterns\Wordplay live?
-
src/Wordplay.php -
tests/Wordplay.php -
vendor/Designpatterns/Wordplay.php - anywhere — Composer searches the whole project
See Also
Section titled “See Also”Answered: 0 / 0 (0%)
Correct: 0 / 0 (0%)