Chapter 8: Test Filtering in PestPHP

Chapter 8: Test Filtering in PestPHP

In this chapter, we'll explore how PestPHP allows you to filter and run specific tests, providing you with a focused and efficient testing experience. Test filtering is a valuable feature, especially when dealing with large test suites, enabling you to run only the tests that matter for a particular scenario or section of your code.

Understanding Test Filtering

PestPHP allows you to filter tests based on their names, making it easy to execute a subset of your test suite. This is particularly useful when you want to focus on a specific test or a group of related tests.

Running Individual Tests

To run a specific test, simply provide the test name as an argument when executing PestPHP:

./vendor/bin/pest path/to/YourTestFile.php

This command will run all tests in the specified file.

Running Tests with a Specific Description

If your test has a description (using it function), you can use the description to run the test:

./vendor/bin/pest --filter="it should perform a specific action"

This command will filter and run the test with the specified description.

Running Tests by Group

PestPHP allows you to group tests using the group function. You can then run tests by group:

./vendor/bin/pest --group=groupName

This command will execute all tests that belong to the specified group.

Running Tests with Specific Annotations

You can use annotations to tag tests and then run only those tests with specific annotations:

./vendor/bin/pest --filter="@annotationName"

This command will filter and run tests that have the specified annotation.

Practical Use Cases

Focusing on a Specific Feature

Suppose you are working on a specific feature and want to run tests related to that feature:

./vendor/bin/pest --filter="FeatureName"

This command will filter and run tests containing "FeatureName" in their names.

Running Only Slow Tests

If you have marked certain tests as slow using annotations, you can run only those tests:

./vendor/bin/pest --filter="@slow"

This command will execute tests that have been annotated as slow.

only()

If you want to run a specific test in your test suite, you can use the only() method.

test('sum', function () {  $result = sum(1, 2);   expect($result)->toBe(3);})->only();

Conclusion

Test filtering in PestPHP provides a powerful mechanism for running specific tests or groups of tests, allowing you to focus your testing efforts and streamline your development workflow. Whether you're working on a specific feature, fixing a bug, or optimizing performance, test filtering ensures that you can validate the relevant parts of your codebase efficiently. In the next chapter, we will explore PestPHP's extensibility and customization, providing you with even greater control over your testing environment.

Did you find this article valuable?

Support Kasenda's Blog by becoming a sponsor. Any amount is appreciated!