Home » Laravel » How to Run a Specific Test in Laravel

How to Run a Specific Test in Laravel

Laravel framework allows you to run tests using the artisan command since the 7.1.1 version. But it runs all available tests. If you want to run a specific test file or a specific test case, you should use additional options.

In this short article, I will explain how to run a specific test in Laravel using the filtering features of the PHPUnit framework.

How to Filter Tests in Laravel

The artisan test command supports the –filter option, which can help with that. It is not an artisan option it comes from PHPUnit and allows to filter tests not only by names but also by data provided by data providers. You can read more details about it in the official documentation. In this article I will show only how to filter tests by their names.

You can create two test classes to reproduce examples in this article: FirstTest and SecondTest with testFoo(), testBar() and testBaz() methods:

php artisan make:test FirstTest namespace Tests\Feature; use Tests\TestCase; class FirstTest extends TestCase { public function testFoo() { $this->assertTrue(true); } public function testBar() { $this->assertFalse(false); } } php artisan make:test SecondTest namespace Tests\Feature; use Tests\TestCase; class SecondTest extends TestCase { public function testBaz() { $this->assertEquals(1, 1); } }

Now, use this command to run all tests and ensure that everything works fine:

php artisan test

If you want to run only tests from the FirstTest class, just specify its name in the –filter option:

php artisan test --filter FirstTest

Also you can specify the method name instead of the class name:

php artisan test --filter testBaz

Often you may have different test methods in different classes with the same name. In this case you can filter by the class and method name together:

php artisan test --filter FirstTest::testBar

Also you may want to add the class namespace, and you can do this, but don’t forget to use quotes:

php artisan test --filter 'Tests\\Feature\\FirstTest::testBar'

You can specify only the last part of the namespace too:

php artisan test --filter 'Feature\\FirstTest::testBar'

Even more, the value of the –filter option can be regular expression, so you can use any combinations of symbols to run only wanted tests. For example:

php artisan test --filter 'Tests\Feature\F[a-z]+Test::testBar'

Wrapping Up

In this short article, you have learned how to run a specific test in Laravel. It can be very helpful when you are developing a test and have to run it again and again to make it work.

Your Reaction

Leave a Comment