Pest allows to set groups for tests. Group can be set for a folder, a file, or a test. Multiple groups can also be assigned.
The group()
function is used to add a group. Here is an example of a specific test.
tests/Feature/ProductsTest.php:
test('api product store successful', function () { $product = [ 'name' => 'Product 1', 'price' => 123 ]; postJson('/api/products', $product) ->assertStatus(201) ->assertJson($product);})->group('api'); test('api product invalid store returns error', function () { $product = [ 'name' => '', 'price' => 123 ]; postJson('/api/products', $product) ->assertStatus(422);})->group('api');
When running tests, the flag --group
should be used with the group name, to filter tests by a group.
We added API tests to the same ProductsTest
file in this course. But, if we moved all API tests to the tests/Feature/Api
folder, we could add a group to a whole folder.
tests/Feature/Api/ProductsTest.php:
use App\Models\Product;use function Pest\Laravel\getJson;use function Pest\Laravel\postJson; test('api returns products list', function () { $product = Product::factory()->create(); $res = getJson('/api/products') ->assertJson([$product->toArray()]); expect($res->content()) ->json() ->toHaveCount(1);}); test('api product store successful', function () { $product = [ 'name' => 'Product 1', 'price' => 123 ]; postJson('/api/products', $product) ->assertStatus(201) ->assertJson($product);}); test('api product invalid store returns error', function () { $product = [ 'name' => '', 'price' => 123 ]; postJson('/api/products', $product) ->assertStatus(422);});
To add a group for a folder, we must add it in the Pest.php
file.
tests/Pest.php:
uses(TestCase::class, RefreshDatabase::class)->in('Feature');uses()->group('api')->in('Feature/Api'); // ...
Because these two test files are for products, we can group them into the products
group.
tests/Feature/ProductsTest.php:
uses()->group('products'); // ...
tests/Feature/Api/ProductsTest.php:
uses()->group('products'); // ...
More about grouping can be found in the official Pest documentation.