Running a Single Test, Skipping Tests, and Other Tips and Tricks

Published on by

Running a Single Test, Skipping Tests, and Other Tips and Tricks image

Nuno Maduro recently shared the ->only() method you can attach to tests with PestPHP. I love targeted ways to run and rerun tests efficiently, and this helper sparked an idea to collect the various ways to filter, skip, and target tests in PHP. This post is by no means exhaustive, but I hope to cover the most important techniques. I'll cover both PHPUnit and Pest, where each tool applies.

Before we get started, here's a look at the only() method Nuno shared that you can attach to individual tests:

 
it('returns a successful response', function () {
    $response = $this->get('/');
 
    $response->assertStatus(200);
})->only();
 
// If you use ->only() with multiple tests it will
// run all of those selected tests.
it('another test', function () {
    // ...
})->only();

Using only() acts as a switch that will target individual tests while you focus on writing code and running tests for that feature. Besides the only() helper, both PHPUnit and Pest provide plenty of ways to isolate, skip, and iterate on a selected set of tests.

Let's take a look!

Filtering Tests

Regardless of a project's size, I prefer to run small groups of tests in isolation while I work on a feature. Learning how to select and filter tests in PHP is an invaluable skill for developers to practice with.

Pest has many options for filtering tests—including the aforementioned ->only() method—using a combination of code or command line flags.

Here are some of the flags Pest offers to filter tests:

pest --dirty
pest --bail # stop execution on first non-passing test
pest --filter 'returns a successful response'
pest --retry # reorders higher priority to failed tests
pest --group|--exclude-group # Like PHPUnit, filter by test groups.
pest --todo # List tests marked as `->todo()`

There are other flags and options for test selection in the Pest CLI Reference.

PHPUnit also has a variety of ways to filter tests that you can use on the command line:

# filter which tests to run
phpunit --filter test_the_application_returns_a_successful_response
# Group flags
phpunit --list-groups # list available groups
phpunit --group api
phpunit --exclude-group live

PHPUnit has a variety of other selection options that you can see by running phpunit --help or visiting the PHP CLI selection documentation. Laravel's Tim MacDonald wrote Tips to Speed up Your Phpunit Tests on Laravel News, which is a resource I recommend to build your test management skills.

Pest offers selections similar to PHPUnit and builds some excellent DX helpers on top of PHPUnit that I find invaluable.

Skipping Tests

Skipping tests is useful when validating your test suite, but know that some tests are either outright broken or a work in progress. A theme I am seeing is that PHPUnit offers the ability to skip tests, and Pest builds on top of that with productive tools that empower you to Brainstorm Tests With PEST Todos and other test-skipping goodies.

When I am writing a new feature, I get tons of ideas as I work on the initial features. Ideas come faster than I can write, so I jump to the test file and start creating a to-do checklist right in the code!

it('returns a successful response', function () {
    $response = $this->get('/');
 
    $response->assertStatus(200);
});
 
it('requires a valid email')->todo();
it('detects Gmail addresses with a "+" as a non-unique email.')->todo();
it('requires a strong password')->todo();

I can then run pest --todo and know exactly where to find new features or tests that I didn't quite finish and want to revisit.

PHPUnit has CLI flags you can use to select/skip tests, such as the --exclude-filter or --exclude-group, which are broader. When you want to skip a specific test, you can use the provided markTestIncomplete() method in the test:

public function test_the_application_returns_a_successful_response(): void
{
    $this->markTestIncomplete('it requires a valid email');
    $response = $this->get('/');
 
    $response->assertStatus(200);
}

If you run the test suite, you will get a note that you have one or more incomplete tests. You can list all of the incomplete tests in more detail using the --display-incomplete flag:

I interpret incomplete tests to be the closest equivalent to Pest's todo() method. While you can achieve similar using markTestAsSkipped(), I would reserve that for skipping tests that shouldn't run on a target platform or given scenario.

Run Tests for Specific PHP or OS Versions

If your codebase supports multiple versions of PHP, sometimes it makes sense to skip specific tests on a given set of PHP versions, Operating systems, or extensions. Both Pest and PHPUnit offer flexible support for these needs.

PHPUnit has a RequiresPhp attribute you can use to target PHP versions in tests, as well as various operating system attributes:

use PHPUnit\Framework\Attributes\RequiresOperatingSystemFamily;
use PHPUnit\Framework\Attributes\RequiresPhp;
 
#[RequiresPhp('<=8.0.0')]
#[RequiresOperatingSystemFamily('Windows')]
public function test_the_application_returns_a_successful_response(): void
{
    $response = $this->get('/');
 
    $response->assertStatus(200);
}

Note: Historically, PHPUnit used the @requires annotation (which is now deprecated) to target multiple types of common preconditions like PHP version, OS, functions, etc.

When you run the above test, it is skipped for systems running a PHP version >8.0.0 or OS other than the Windows family. Running the test suite with --display-skipped gives you details on any skipped tests based on these attributes:

As part of Pest's Skipping Tests docs, you can use the following methods to skip certain PHP versions, OS versions, etc.

it('has home', function () {
    //
})->skipOnPhp('>=8.0.0');
 
it('has home', function () {
    //
})->skipOnWindows(); // or skipOnMac() or skipOnLinux() ...
    
it('has home', function() {
    //
})->onlyOnWindows(); // or onlyOnMac() or onlyOnLinux() ...

Running a Single Test From Your Editor

The last thing to mention is that IDEs offer ways to quickly run individual tests, groups of tests, all tests in one file, etc., with quick command shortcuts. The Better PHPUnit VS Code Extension supports both PHPUnit and Pest, and provides the following features:

  • Run a test method
  • Run a test file
  • Run the entire suite
  • Run a previous test

PHPStorm offers a ton of useful ways to run (and rerun) tests with shortcuts and UI icons, making it super easy to run a test from the test file without jumping to the command line: See the PhpStorm documentation for details on setting up testing shortcuts and tools for both PHPUnit and Pest.

An honorable mention is the sublime-phpunit plugin that gives you the ability to run Run individual unit tests and files directly from Sublime.

What other IDE and text editor tools do you use to automate running tests? Let us know!

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
PHP and LLMs with Alfred Nutile image

PHP and LLMs with Alfred Nutile

Read article
PHP 8.4 Release Candidate 1 is here image

PHP 8.4 Release Candidate 1 is here

Read article
Laravel Config Checker Package image

Laravel Config Checker Package

Read article
Laravel 11.24 Released image

Laravel 11.24 Released

Read article
A Deep Dive into Sessions in Laravel image

A Deep Dive into Sessions in Laravel

Read article
The September 2024 Laravel Worldwide Meetup is Today image

The September 2024 Laravel Worldwide Meetup is Today

Read article