Back to Course |
Testing in Laravel 11: Advanced Level

Customize Default Test Stubs

Generally, when you run php artisan make:test, it adds an example test, which is pretty meaningless. So, let's talk about generating a new test class with our custom code.


For example, let's generate a new test.

php artisan make:test SomeTest

When you open that test file, you see an example test that has been added.

tests/Feature/SomeTest.php:

<?php
 
test('example', function () {
$response = $this->get('/');
 
$response->assertStatus(200);
});

When using PHPUnit, the generated test looks like the one below. Comments were also added for the test.

tests/Feature/SomeTest.php:

<?php
 
namespace Tests\Feature;
 
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
 
class SomeTest extends TestCase
{
/**
* A basic feature test example.
*/
public function test_example(): void
{
$response = $this->get('/');
 
$response->assertStatus(200);
}
}

What if you want to avoid making those changes every time and you want to change the template for the default test?

In Laravel, the default generated code can be changed when generating using an Artisan command by changing the so-called stubs, not only for test files. First, the stubs must be published.

php artisan stub:publish

After publishing the stubs, you will have a stubs folder. In this folder, you will find stubs for Pest and PHPUnit.

For example, you want to create an empty test without any assertions. Then, you modify the stub you need.

stubs/pest.stub:

<?php
 
test('', function () {
 
});

After this change, creating a new test using php artisan make:test NewTest no longer adds assertions or examples for the test name.

tests/Feature/NewTest.php

<?php
 
test('', function () {
 
});