4,000 emails/month for free | Mailtrap sends real emails now!

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.

image
Tinkerwell

Enjoy coding and debugging in an editor designed for fast feedback and quick iterations. It's like a shell for your application – but with multi-line editing, code completion, and more.

Visit Tinkerwell
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

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

Bacancy
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud
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
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

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

Lucky Media
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

The latest

View all →
Install Laravel Package Guidelines and Skills in Boost image

Install Laravel Package Guidelines and Skills in Boost

Read article
Bagisto Visual: Theme Framework with Visual Editor for Laravel E-commerce image

Bagisto Visual: Theme Framework with Visual Editor for Laravel E-commerce

Read article
Clawdbot Rebrands to Moltbot After Trademark Request From Anthropic image

Clawdbot Rebrands to Moltbot After Trademark Request From Anthropic

Read article
Automate Laravel Herd Worktrees with This Claude Code Skill image

Automate Laravel Herd Worktrees with This Claude Code Skill

Read article
Laravel Boost v2.0 Released with Skills Support image

Laravel Boost v2.0 Released with Skills Support

Read article
Laravel Debugbar v4.0.0 is released image

Laravel Debugbar v4.0.0 is released

Read article