カスタム ヘルパー

テストを記述するための関数型アプローチに移行する場合、テストクラスの保護されたメソッドまたはプライベートメソッドとして記述されていたヘルパーをどこに配置するかを考える必要がありま す。Pest を使用する場合、これらのヘルパーメソッドは単純な関数に変換する必要があります。

たとえば、ヘルパーが特定のテストファイルに固有の場合、そのヘルパーをテストファイルに直接作成できます。ヘルパー内で通常は $this を介して利用可能なテストクラスのインスタンスにアクセスするには、test() 関数を呼び出します。

1use App\Models\User;
2use Tests\TestCase;
3 
4function asAdmin(): TestCase
5{
6 $user = User::factory()->create([
7 'admin' => true,
8 ]);
9 
10 return test()->actingAs($user);
11}
12 
13it('can manage users', function () {
14 asAdmin()->get('/users')->assertOk();
15})

注: ヘルパーがカスタム期待値を作成する場合は、代わりに カスタム期待値 を記述する必要があります。

テストヘルパーがテストスイート全体を通して利用される場合、それらを tests/Pest.php または tests/Helpers.php ファイル内で定義できます。それ以外の方法として、独自のヘルパーファイルを収容する tests/Helpers ディレクトリを作成することもできます。これらのオプションはすべて Pest によって自動的にロードされます。

1use App\Clients\PaymentClient;
2use Mockery;
3 
4// tests/Pest.php or tests/Helpers.php
5function mockPayments(): object
6{
7 $client = Mockery::mock(PaymentClient::class);
8 
9 //
10 
11 return $client;
12}
13 
14// tests/Feature/PaymentsTest.php
15it('may buy a book', function () {
16 $client = mockPayments();
17 
18 //
19})

ヘルパーメソッドを関数として定義する代わりに、基本テストクラスで保護されたメソッドを定義して、$this 変数を使用してテストケースでそれらにアクセスすることもできます。

1use App\Clients\PaymentClient;
2use PHPUnit\Framework\TestCase as BaseTestCase;
3use Mockery;
4 
5// tests/TestCase.php
6class TestCase extends BaseTestCase
7{
8 protected function mockPayments(): void
9 {
10 $client = Mockery::mock(PaymentClient::class);
11 
12 //
13 
14 return $client;
15 }
16}
17 
18// tests/Pest.php
19pest()->extend(TestCase::class)->in('Feature');
20 
21// tests/Feature/PaymentsTest.php
22it('may buy a book', function () {
23 $client = $this->mockPayments();
24 
25 //
26})

このセクションでは、カスタム ヘルパーの作成について説明しました。さらに深く掘り下げると、カスタム期待値を生成したいと思うかもしれません。次の章、カスタム期待値でそのトピックに飛び込みましょう: