Readouble

Laravel 8.x HTTPテスト

イントロダクションIntroduction

Laravelは、アプリケーションにHTTPリクエストを送信し、レスポンスを調べるための非常に流暢なAPIを提供しています。例として、以下に定義している機能テストをご覧ください。Laravel provides a very fluent API for making HTTP requests to your application and examining the responses. For example, take a look at the feature test defined below:

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\TestCase;

class ExampleTest extends TestCase
{
    /**
     * 基本的なテスト例
     *
     * @return void
     */
    public function test_a_basic_request()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}

getメソッドはアプリケーションにGETリクエストを送信し、assertStatusメソッドは返えされたレスポンスに指定するHTTPステータスコードが必要であることを宣言しています。この単純なアサートに加え、Laravelはレスポンスヘッダ、コンテンツ、JSON構造などを検査するためにさまざまなアサートも用意しています。The get method makes a GET request into the application, while the assertStatus method asserts that the returned response should have the given HTTP status code. In addition to this simple assertion, Laravel also contains a variety of assertions for inspecting the response headers, content, JSON structure, and more.

リクエストの作成Making Requests

アプリケーションにリクエストを送信するには、テスト内でgetpostputpatchdeleteメソッドを呼び出してください。これらのメソッドは、実際にはアプリケーションへ「本当の」HTTPリクエストを発行しません。代わりに、ネットワークリクエスト全体が内部でシミュレートされます。To make a request to your application, you may invoke the get, post, put, patch, or delete methods within your test. These methods do not actually issue a "real" HTTP request to your application. Instead, the entire network request is simulated internally.

テストリクエストメソッドは、Illuminate\Http\Responseインスタンスを返す代わりに、Illuminate\Testing\TestResponseのインスタンスを返します。これは、アプリケーションのレスポンスの検査を可能にするさまざまな有用なアサートを提供します。Instead of returning an Illuminate\Http\Response instance, test request methods return an instance of Illuminate\Testing\TestResponse, which provides a variety of helpful assertions[#available-assertions] that allow you to inspect your application's responses:

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\TestCase;

class ExampleTest extends TestCase
{
    /**
     * 基本的なテスト例
     *
     * @return void
     */
    public function test_a_basic_request()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}

通常、各テストはアプリケーションに対して 1 つのリクエストしか行わないようにしてください。1つのテストメソッドの中で複数のリクエストを実行すると、 予期せぬ動作が起きる可能性があります。In general, each of your tests should only make one request to your application. Unexpected behavior may occur if multiple requests are executed within a single test method.

lightbulb">Tip!! 利便性を良くするため、テストの実行時にCSRFミドルウェアを自動で無効にします。{tip} For convenience, the CSRF middleware is automatically disabled when running tests.

リクエストヘッダのカスタマイズCustomizing Request Headers

withHeadersメソッドを使用して、アプリケーションに送信する前にリクエストのヘッダをカスタマイズできます。このメソッドを使用すると、リクエストに必要なカスタムヘッダを追加できます。You may use the withHeaders method to customize the request's headers before it is sent to the application. This method allows you to add any custom headers you would like to the request:

<?php

namespace Tests\Feature;

use Tests\TestCase;

class ExampleTest extends TestCase
{
    /**
     * 基本的な機能テストの例
     *
     * @return void
     */
    public function test_interacting_with_headers()
    {
        $response = $this->withHeaders([
            'X-Header' => 'Value',
        ])->post('/user', ['name' => 'Sally']);

        $response->assertStatus(201);
    }
}

クッキーCookies

リクエストを行う前に、withCookieまたはwithCookiesメソッドを使用してクッキー値を設定できます。withCookieメソッドは2つの引数としてCookieの名前と値を引数に取りますが、withCookiesメソッドは名前/値ペアの配列を引数に取ります。You may use the withCookie or withCookies methods to set cookie values before making a request. The withCookie method accepts a cookie name and value as its two arguments, while the withCookies method accepts an array of name / value pairs:

<?php

namespace Tests\Feature;

use Tests\TestCase;

class ExampleTest extends TestCase
{
    public function test_interacting_with_cookies()
    {
        $response = $this->withCookie('color', 'blue')->get('/');

        $response = $this->withCookies([
            'color' => 'blue',
            'name' => 'Taylor',
        ])->get('/');
    }
}

セッション/認証Session / Authentication

Laravelは、HTTPテスト中にセッションを操作ためヘルパをいくつか提供しています。まず、withSessionメソッドへ配列を渡し、セッションデータを設定できます。これは、アプリケーションにリクエストを発行する前に、セッションにデータをロードする場合に役立ちます。Laravel provides several helpers for interacting with the session during HTTP testing. First, you may set the session data to a given array using the withSession method. This is useful for loading the session with data before issuing a request to your application:

<?php

namespace Tests\Feature;

use Tests\TestCase;

class ExampleTest extends TestCase
{
    public function test_interacting_with_the_session()
    {
        $response = $this->withSession(['banned' => false])->get('/');
    }
}

Laravelのセッションは通常、現在認証しているユーザーの状態を維持するために使用します。したがって、actingAsヘルパメソッドは、指定ユーザーを現在のユーザーとして認証する簡単な方法を提供します。たとえば、モデルファクトリを使用して、ユーザーを生成および認証できます。Laravel's session is typically used to maintain state for the currently authenticated user. Therefore, the actingAs helper method provides a simple way to authenticate a given user as the current user. For example, we may use a model factory[/docs/{{version}}/database-testing#writing-factories] to generate and authenticate a user:

<?php

namespace Tests\Feature;

use App\Models\User;
use Tests\TestCase;

class ExampleTest extends TestCase
{
    public function test_an_action_that_requires_authentication()
    {
        $user = User::factory()->create();

        $response = $this->actingAs($user)
                         ->withSession(['banned' => false])
                         ->get('/');
    }
}

actingAsメソッドの2番目の引数としてガード名を渡すことにより、特定のユーザーを認証するために使用するガードを指定することもできます。You may also specify which guard should be used to authenticate the given user by passing the guard name as the second argument to the actingAs method:

$this->actingAs($user, 'web')

レスポンスのデバッグDebugging Responses

アプリケーションにテストリクエストを送ったあとは、dumpdumpHeadersdumpSessionメソッドを使用して、レスポンスの内容を調べてデバッグできます。After making a test request to your application, the dump, dumpHeaders, and dumpSession methods may be used to examine and debug the response contents:

<?php

namespace Tests\Feature;

use Tests\TestCase;

class ExampleTest extends TestCase
{
    /**
     * 基本的なテスト例
     *
     * @return void
     */
    public function test_basic_test()
    {
        $response = $this->get('/');

        $response->dumpHeaders();

        $response->dumpSession();

        $response->dump();
    }
}

あるいは、ddddHeadersddSessionメソッドを使って、レスポンスに関する情報をダンプしてから、実行を停止することもできます。Alternatively, you may use the dd, ddHeaders, and ddSession methods to dump information about the response and then stop execution:

<?php

namespace Tests\Feature;

use Tests\TestCase;

class ExampleTest extends TestCase
{
    /**
     * 基本的なテスト例
     *
     * @return void
     */
    public function test_basic_test()
    {
        $response = $this->get('/');

        $response->ddHeaders();

        $response->ddSession();

        $response->dd();
    }
}

例外処理Exception Handling

時には、アプリケーションが特定の例外を投げているかをテストしたい場合も起きます。例外がLaravelの例外ハンドラに捕捉され、HTTPレスポンスとして返されないようにするために、リクエストを行う前に、withoutExceptionHandlingメソッドを呼び出してください。Sometimes you may want to test that your application is throwing a specific exception. To ensure that the exception does not get caught by Laravel's exception handler and returned as an HTTP response, you may invoke the withoutExceptionHandling method before making your request:

$response = $this->withoutExceptionHandling()->get('/');

加えて、PHP 言語やアプリケーションが使用しているライブラリで廃止された機能をアプリケーションが使用していないことを確認したい場合は、リクエストを行う前にwithoutDeprecationHandlingメソッドを呼び出してください。この廃止例外の処理を無効にすると、deprecationの警告が例外に変換され、テストが失敗するようになります。In addition, if you would like to ensure that your application is not utilizing features that have been deprecated by the PHP language or the libraries your application is using, you may invoke the withoutDeprecationHandling method before making your request. When deprecation handling is disabled, deprecation warnings will be converted to exceptions, thus causing your test to fail:

$response = $this->withoutDeprecationHandling()->get('/');

JSON APIのテストTesting JSON APIs

Laravelは、JSON APIとそのレスポンスをテストするためのヘルパもいくつか提供しています。たとえば、jsongetJsonpostJsonputJsonpatchJsondeleteJsonoptionsJsonメソッドを使用して、さまざまなHTTP動詞でJSONリクエストを発行できます。これらのメソッドにデータとヘッダを簡単に渡すこともできます。まず、/api/userに対してPOSTリクエストを作成し、期待されるJSONデータが返されたことを宣言するテストを作成しましょう。Laravel also provides several helpers for testing JSON APIs and their responses. For example, the json, getJson, postJson, putJson, patchJson, deleteJson, and optionsJson methods may be used to issue JSON requests with various HTTP verbs. You may also easily pass data and headers to these methods. To get started, let's write a test to make a POST request to /api/user and assert that the expected JSON data was returned:

<?php

namespace Tests\Feature;

use Tests\TestCase;

class ExampleTest extends TestCase
{
    /**
     * 基本的な機能テストの例
     *
     * @return void
     */
    public function test_making_an_api_request()
    {
        $response = $this->postJson('/api/user', ['name' => 'Sally']);

        $response
            ->assertStatus(201)
            ->assertJson([
                'created' => true,
            ]);
    }
}

さらに、JSONレスポンスデータは、レスポンス上の配列変数としてアクセスできるため、JSONレスポンス内で返された個々の値を調べるのに便利です。In addition, JSON response data may be accessed as array variables on the response, making it convenient for you to inspect the individual values returned within a JSON response:

$this->assertTrue($response['created']);

lightbulb">Tip!! assertJsonメソッドはレスポンスを配列に変換し、PHPUnit::assertArraySubsetを利用して、指定する配列がアプリケーションによって返されるJSONレスポンス内に存在することを確認しています。したがって、JSONレスポンスに他のプロパティがある場合でも、指定するフラグメントが存在する限り、このテストは合格します。{tip} The assertJson method converts the response to an array and utilizes PHPUnit::assertArraySubset to verify that the given array exists within the JSON response returned by the application. So, if there are other properties in the JSON response, this test will still pass as long as the given fragment is present.

厳密なJSON一致のアサートAsserting Exact JSON Matches

前述のように、assertJsonメソッドを使用して、JSONのフラグメントがJSONレスポンス内に存在することをアサートできます。指定した配列とアプリケーションが返してきたJSONが完全に一致することを確認したい場合は、assertExactJsonメソッドを使用する必要があります。As previously mentioned, the assertJson method may be used to assert that a fragment of JSON exists within the JSON response. If you would like to verify that a given array exactly matches the JSON returned by your application, you should use the assertExactJson method:

<?php

namespace Tests\Feature;

use Tests\TestCase;

class ExampleTest extends TestCase
{
    /**
     * 基本的な機能テストの例
     *
     * @return void
     */
    public function test_asserting_an_exact_json_match()
    {
        $response = $this->postJson('/user', ['name' => 'Sally']);

        $response
            ->assertStatus(201)
            ->assertExactJson([
                'created' => true,
            ]);
    }
}

JSONパスでのアサートAsserting On JSON Paths

JSONレスポンスの指定パスに指定データが含まれていることを確認する場合は、assertJsonPathメソッドを使用する必要があります。If you would like to verify that the JSON response contains the given data at a specified path, you should use the assertJsonPath method:

<?php

namespace Tests\Feature;

use Tests\TestCase;

class ExampleTest extends TestCase
{
    /**
     * 基本的な機能テストの例
     *
     * @return void
     */
    public function test_asserting_a_json_paths_value()
    {
        $response = $this->postJson('/user', ['name' => 'Sally']);

        $response
            ->assertStatus(201)
            ->assertJsonPath('team.owner.name', 'Darian');
    }
}

FluentなJSONテストFluent JSON Testing

また、LaravelはアプリケーションのJSONレスポンスを流暢にテストする美しい方法を提供しています。まず始めに、assertJsonメソッドにクロージャを渡します。このクロージャは、アプリケーションが返すJSONに対してアサートを行うために使用できる、Illuminate\Testing\Fluent\AssertableJsonのインスタンスで呼び出されます。whereメソッドはJSONの特定の属性に対してアサートを行うために使用でき、missingメソッドはJSONに特定の属性がないことをアサートするために使用できます。Laravel also offers a beautiful way to fluently test your application's JSON responses. To get started, pass a closure to the assertJson method. This closure will be invoked with an instance of Illuminate\Testing\Fluent\AssertableJson which can be used to make assertions against the JSON that was returned by your application. The where method may be used to make assertions against a particular attribute of the JSON, while the missing method may be used to assert that a particular attribute is missing from the JSON:

use Illuminate\Testing\Fluent\AssertableJson;

/**
 * 基本的な機能テストの例
 *
 * @return void
 */
public function test_fluent_json()
{
    $response = $this->getJson('/users/1');

    $response
        ->assertJson(fn (AssertableJson $json) =>
            $json->where('id', 1)
                 ->where('name', 'Victoria Faith')
                 ->missing('password')
                 ->etc()
        );
}

etcメソッドを理解するUnderstanding The etc Method

上記の例では、アサートのチェーンの最後でetcメソッドを呼び出したことに気づかれた方もいらっしゃるでしょう。このメソッドはLaravelへJSONオブジェクト中に他の属性が存在する可能性があることを伝えます。etcメソッドが使用されていない場合は、JSONオブジェクトに他の属性が存在していることをアサートしていないため、テストは失敗します。In the example above, you may have noticed we invoked the etc method at the end of our assertion chain. This method informs Laravel that there may be other attributes present on the JSON object. If the etc method is not used, the test will fail if other attributes that you did not make assertions against exist on the JSON object.

この動作の意図は、属性に対して明示的にアサーションを行うか、etc メソッドで追加の属性を明示的に許可することで、JSONレスポンスで意図せず機密情報を公開してしまうことを防ぐことにあります。The intention behind this behavior is to protect you from unintentionally exposing sensitive information in your JSON responses by forcing you to either explicitly make an assertion against the attribute or explicitly allow additional attributes via the etc method.

属性の有無をアサートするAsserting Attribute Presence / Absence

属性が存在しているかどうかをアサートするには、hasmissingメソッドを使います。To assert that an attribute is present or absent, you may use the has and missing methods:

$response->assertJson(fn (AssertableJson $json) =>
    $json->has('data')
         ->missing('message')
);

さらに、hasAllmissingAllメソッドは、複数の属性の有無を同時にアサートできます。In addition, the hasAll and missingAll methods allow asserting the presence or absence of multiple attributes simultaneously:

$response->assertJson(fn (AssertableJson $json) =>
    $json->hasAll('status', 'data')
         ->missingAll('message', 'code')
);

hasAnyメソッドを使用して、指定する属性リスト中に少なくとも1つ存在しているか判断できます。You may use the hasAny method to determine if at least one of a given list of attributes is present:

$response->assertJson(fn (AssertableJson $json) =>
    $json->has('status')
         ->hasAny('data', 'message', 'code')
);

JSONコレクションに対するアサートAsserting Against JSON Collections

多くの場合、ルートは複数のユーザーなど、複数の項目を含むJSONレスポンスを返します。Often, your route will return a JSON response that contains multiple items, such as multiple users:

Route::get('/users', function () {
    return User::all();
});

このような状況では、レスポンスに含まれているユーザーに対するアサートを行うために、fluentなJSONオブジェクトのhasメソッドを使用することができます。例として、JSONレスポンスに3つのユーザーが含まれていることをアサートしましょう。次に、firstメソッドを使用して、コレクション内の最初のユーザーに関するいくつかのアサートを行います。firstメソッドは、JSONコレクション内の最初のオブジェクトに関するアサートを行うために使用できる別のアサートJSON文字列を受信するクロージャを引数に取ります。In these situations, we may use the fluent JSON object's has method to make assertions against the users included in the response. For example, let's assert that the JSON response contains three users. Next, we'll make some assertions about the first user in the collection using the first method. The first method accepts a closure which receives another assertable JSON string that we can use to make assertions about the first object in the JSON collection:

$response
    ->assertJson(fn (AssertableJson $json) =>
        $json->has(3)
             ->first(fn ($json) =>
                $json->where('id', 1)
                     ->where('name', 'Victoria Faith')
                     ->missing('password')
                     ->etc()
             )
    );

JSONコレクションをスコープするアサーションScoping JSON Collection Assertions

時々、アプリケーションのルートは名前付きキーが割り当てられているJSONコレクションを返します。Sometimes, your application's routes will return JSON collections that are assigned named keys:

Route::get('/users', function () {
    return [
        'meta' => [...],
        'users' => User::all(),
    ];
})

これらのルートをテストするときは、コレクション内の項目数に対してhasメソッドを使えます。さらに、hasメソッドを使用してアサーションチェーンをスコープできます。When testing these routes, you may use the has method to assert against the number of items in the collection. In addition, you may use the has method to scope a chain of assertions:

$response
    ->assertJson(fn (AssertableJson $json) =>
        $json->has('meta')
             ->has('users', 3)
             ->has('users.0', fn ($json) =>
                $json->where('id', 1)
                     ->where('name', 'Victoria Faith')
                     ->missing('password')
                     ->etc()
             )
    );

ただし、hasコレクションにhasコレクションにアサートする2つの別々の呼び出しをするのではなく、クロージャを3番目の引数に渡す呼び出し一つにまとめられます。これで、クロージャが自動的に呼び出され、コレクション内の最初の項目にスコープされます。However, instead of making two separate calls to the has method to assert against the users collection, you may make a single call which provides a closure as its third parameter. When doing so, the closure will automatically be invoked and scoped to the first item in the collection:

$response
    ->assertJson(fn (AssertableJson $json) =>
        $json->has('meta')
             ->has('users', 3, fn ($json) =>
                $json->where('id', 1)
                     ->where('name', 'Victoria Faith')
                     ->missing('password')
                     ->etc()
             )
    );

JSONタイプのアサートAsserting JSON Types

JSONレスポンス内のプロパティが特定の型のものであることをアサートできます。Illuminate\Testing\Fluent\AssertableJsonクラスは、これを行うwhereTypewhereAllTypeメソッドを提供しています。You may only want to assert that the properties in the JSON response are of a certain type. The Illuminate\Testing\Fluent\AssertableJson class provides the whereType and whereAllType methods for doing just that:

$response->assertJson(fn (AssertableJson $json) =>
    $json->whereType('id', 'integer')
         ->whereAllType([
            'users.0.name' => 'string',
            'meta' => 'array'
        ])
);

複数のタイプを指定するには | 文字を使用するか、タイプの配列を whereType メソッドの 2 番目のパラメータとして渡します。レスポンスの値がリストアップされたタイプのいずれかであれば、アサーションは成功します。You may specify multiple types using the | character, or passing an array of types as the second parameter to the whereType method. The assertion will be successful if the response value is any of the listed types:

$response->assertJson(fn (AssertableJson $json) =>
    $json->whereType('name', 'string|null')
         ->whereType('id', ['string', 'integer'])
);

whereTypewhereAllTypeメソッドは、stringintegerdoublebooleanarraynullタイプを認識します。The whereType and whereAllType methods recognize the following types: string, integer, double, boolean, array, and null.

ファイルアップロードのテストTesting File Uploads

Illuminate\Http\UploadedFileクラスは、テスト用のダミーファイルまたは画像を生成するために使用できるfakeメソッドを提供しています。これをStorageファサードのfakeメソッドと組み合わせると、ファイルアップロードのテストが大幅に簡素化されます。たとえば、次の2つの機能を組み合わせて、アバターのアップロードフォームを簡単にテストできます。The Illuminate\Http\UploadedFile class provides a fake method which may be used to generate dummy files or images for testing. This, combined with the Storage facade's fake method, greatly simplifies the testing of file uploads. For example, you may combine these two features to easily test an avatar upload form:

<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class ExampleTest extends TestCase
{
    public function test_avatars_can_be_uploaded()
    {
        Storage::fake('avatars');

        $file = UploadedFile::fake()->image('avatar.jpg');

        $response = $this->post('/avatar', [
            'avatar' => $file,
        ]);

        Storage::disk('avatars')->assertExists($file->hashName());
    }
}

指定ファイルが存在しないことを宣言したい場合は、Storageファサードが提供するassertMissingメソッドを使用できます。If you would like to assert that a given file does not exist, you may use the assertMissing method provided by the Storage facade:

Storage::fake('avatars');

// ...

Storage::disk('avatars')->assertMissing('missing.jpg');

fakeファイルのカスタマイズFake File Customization

UploadedFileクラスが提供するfakeメソッドを使用してファイルを作成する場合、アプリケーションのバリデーションルールをより適切にテストするために、画像の幅、高さ、およびサイズ(キロバイト単位)を指定できます。When creating files using the fake method provided by the UploadedFile class, you may specify the width, height, and size of the image (in kilobytes) in order to better test your application's validation rules:

UploadedFile::fake()->image('avatar.jpg', $width, $height)->size(100);

画像に加えて、createメソッドを使用して他のタイプのファイルも作成できます。In addition to creating images, you may create files of any other type using the create method:

UploadedFile::fake()->create('document.pdf', $sizeInKilobytes);

必要に応じて、メソッドに$mimeType引数を渡し、ファイルが返すMIMEタイプを明示的に定義できます。If needed, you may pass a $mimeType argument to the method to explicitly define the MIME type that should be returned by the file:

UploadedFile::fake()->create(
    'document.pdf', $sizeInKilobytes, 'application/pdf'
);

ビューのテストTesting Views

Laravelを使用すると、アプリケーションに対してシミュレートするHTTPリクエストを作成せずにビューをレンダーすることもできます。それには、テスト内でviewメソッドを呼び出してください。viewメソッドは、ビュー名とオプションのデータ配列を引数に取ります。このメソッドはIlluminate\Testing\TestViewのインスタンスを返します。これは、ビューのコンテンツに関するアサートを簡単に作成するためのメソッドをいくつか提供しています。Laravel also allows you to render a view without making a simulated HTTP request to the application. To accomplish this, you may call the view method within your test. The view method accepts the view name and an optional array of data. The method returns an instance of Illuminate\Testing\TestView, which offers several methods to conveniently make assertions about the view's contents:

<?php

namespace Tests\Feature;

use Tests\TestCase;

class ExampleTest extends TestCase
{
    public function test_a_welcome_view_can_be_rendered()
    {
        $view = $this->view('welcome', ['name' => 'Taylor']);

        $view->assertSee('Taylor');
    }
}

TestViewクラスは、次のアサートメソッドを提供します。assertSeeassertSeeInOrderassertSeeTextassertSeeTextInOrderassertDontSeeassertDontSeeTextThe TestView class provides the following assertion methods: assertSee, assertSeeInOrder, assertSeeText, assertSeeTextInOrder, assertDontSee, and assertDontSeeText.

必要に応じて、TestViewインスタンスを文字列にキャストすることで、レンダリングされた素のビューコンテンツを取得できます。If needed, you may get the raw, rendered view contents by casting the TestView instance to a string:

$contents = (string) $this->view('welcome');

エラーの共有Sharing Errors

一部のビューは、Laravelが提供するグローバルエラーバッグで共有されるエラーに依存する場合があります。エラーバッグをエラーメッセージでハイドレイトするには、withViewErrorsメソッドを使用できます。Some views may depend on errors shared in the global error bag provided by Laravel[/docs/{{version}}/validation#quick-displaying-the-validation-errors]. To hydrate the error bag with error messages, you may use the withViewErrors method:

$view = $this->withViewErrors([
    'name' => ['Please provide a valid name.']
])->view('form');

$view->assertSee('Please provide a valid name.');

BladeとコンポーネントのレンダーRendering Blade & Components

必要に応じて、bladeメソッドを使用して、素のBlade文字列を評価およびレンダーできます。viewメソッドと同様に、bladeメソッドはIlluminate\Testing\TestViewのインスタンスを返します。If necessary, you may use the blade method to evaluate and render a raw Blade[/docs/{{version}}/blade] string. Like the view method, the blade method returns an instance of Illuminate\Testing\TestView:

$view = $this->blade(
    '<x-component :name="$name" />',
    ['name' => 'Taylor']
);

$view->assertSee('Taylor');

componentメソッドを使用して、ブレードコンポーネントを評価およびレンダーできます。viewメソッドと同様に、componentメソッドはIlluminate\Testing\TestViewのインスタンスを返します。You may use the component method to evaluate and render a Blade component[/docs/{{version}}/blade#components]. Like the view method, the component method returns an instance of Illuminate\Testing\TestView:

$view = $this->component(Profile::class, ['name' => 'Taylor']);

$view->assertSee('Taylor');

利用可能なアサートAvailable Assertions

レスポンスのアサートResponse Assertions

LaravelのIlluminate\Testing\TestResponseクラスは、アプリケーションをテストするときに利用できるさまざまなカスタムアサートメソッドを提供します。これらのアサートは、jsongetpostputdeleteテストメソッドが返すレスポンスからアクセスできます。Laravel's Illuminate\Testing\TestResponse class provides a variety of custom assertion methods that you may utilize when testing your application. These assertions may be accessed on the response that is returned by the json, get, post, put, and delete test methods:

assertCookieassertCookie

レスポンスに指定するクッキーが含まれていることを宣言します。Assert that the response contains the given cookie:

$response->assertCookie($cookieName, $value = null);

assertCookieExpiredassertCookieExpired

レスポンスに指定するクッキーが含まれており、有効期限が切れていることを宣言します。Assert that the response contains the given cookie and it is expired:

$response->assertCookieExpired($cookieName);

assertCookieNotExpiredassertCookieNotExpired

レスポンスに指定するクッキーが含まれており、有効期限が切れていないことを宣言します。Assert that the response contains the given cookie and it is not expired:

$response->assertCookieNotExpired($cookieName);

assertCookieMissingassertCookieMissing

レスポンスに指定するクッキーが含まれていないことを宣言します。Assert that the response does not contains the given cookie:

$response->assertCookieMissing($cookieName);

assertCreatedassertCreated

レスポンスに201 HTTPステータスコードがあることを宣言します。Assert that the response has a 201 HTTP status code:

$response->assertCreated();

assertDontSeeassertDontSee

指定する文字列が、アプリケーションが返すレスポンスに含まれていないことを宣言します。このアサートは、2番目の引数にfalseを渡さない限り、指定する文字列を自動的にエスケープします。Assert that the given string is not contained within the response returned by the application. This assertion will automatically escape the given string unless you pass a second argument of false:

$response->assertDontSee($value, $escaped = true);

assertDontSeeTextassertDontSeeText

指定する文字列がレスポンステキストに含まれていないことを宣言します。このアサートは、2番目の引数にfalseを渡さない限り、指定する文字列を自動的にエスケープします。このメソッドは、アサートを作成する前に、レスポンスコンテンツをstrip_tags PHP関数へ渡します。Assert that the given string is not contained within the response text. This assertion will automatically escape the given string unless you pass a second argument of false. This method will pass the response content to the strip_tags PHP function before making the assertion:

$response->assertDontSeeText($value, $escaped = true);

assertDownloadassertDownload

レスポンスが「ダウンロード」であることを宣言します。通常、Response::downloadレスポンス、BinaryFileResponse、またはStorage::downloadレスポンスを返すルートが起動されたことを意味します。Assert that the response is a "download". Typically, this means the invoked route that returned the response returned a Response::download response, BinaryFileResponse, or Storage::download response:

$response->assertDownload();

お望みであれば、ダウンロード可能なファイルに指定のファイル名が付与されていることを宣言することもできます。If you wish, you may assert that the downloadable file was assigned a given file name:

$response->assertDownload('image.jpg');

assertExactJsonassertExactJson

レスポンスに、完全一致する指定JSONデータが含まれていることを宣言します。Assert that the response contains an exact match of the given JSON data:

$response->assertExactJson(array $data);

assertForbiddenassertForbidden

レスポンスにForbidden(403)HTTPステータスコードがあることを宣言します。Assert that the response has a forbidden (403) HTTP status code:

$response->assertForbidden();

assertHeaderassertHeader

指定するヘッダと値がレスポンスに存在することを宣言します。Assert that the given header and value is present on the response:

$response->assertHeader($headerName, $value = null);

assertHeaderMissingassertHeaderMissing

指定するヘッダがレスポンスに存在しないことを宣言します。Assert that the given header is not present on the response:

$response->assertHeaderMissing($headerName);

assertJsonassertJson

レスポンスに指定するJSONデータが含まれていることを宣言します。Assert that the response contains the given JSON data:

$response->assertJson(array $data, $strict = false);

assertJsonメソッドはレスポンスを配列に変換し、PHPUnit::assertArraySubsetを利用して、指定する配列がアプリケーションが返すJSONレスポンス内に存在しているかを確認します。したがって、JSONレスポンスに他のプロパティがある場合でも、指定するフラグメントが存在する限り、このテストは合格します。The assertJson method converts the response to an array and utilizes PHPUnit::assertArraySubset to verify that the given array exists within the JSON response returned by the application. So, if there are other properties in the JSON response, this test will still pass as long as the given fragment is present.

assertJsonCountassertJsonCount

レスポンスJSONに、指定するキーに予想されるアイテム数の配列があることを宣言します。Assert that the response JSON has an array with the expected number of items at the given key:

$response->assertJsonCount($count, $key = null);

assertJsonFragmentassertJsonFragment

レスポンス中のどこかに指定JSONデータが含まれていることを宣言します。Assert that the response contains the given JSON data anywhere in the response:

Route::get('/users', function () {
    return [
        'users' => [
            [
                'name' => 'Taylor Otwell',
            ],
        ],
    ];
});

$response->assertJsonFragment(['name' => 'Taylor Otwell']);

assertJsonMissingassertJsonMissing

レスポンスに指定するJSONデータが含まれていないことを宣言します。Assert that the response does not contain the given JSON data:

$response->assertJsonMissing(array $data);

assertJsonMissingExactassertJsonMissingExact

レスポンスに完全一致するJSONデータが含まれていないことを宣言します。Assert that the response does not contain the exact JSON data:

$response->assertJsonMissingExact(array $data);

assertJsonMissingValidationErrorsassertJsonMissingValidationErrors

指定するキーのJSONバリデーションエラーがレスポンスにないことを宣言します。Assert that the response has no JSON validation errors for the given keys:

$response->assertJsonMissingValidationErrors($keys);

lightbulb">Tip!! より一般的なassertValidメソッドを使用して、JSONで返されたレスポンスにバリデーションエラーがなく、かつセッションストレージにエラーが一時保存されていないことを宣言できます。{tip} The more generic assertValid[#assert-valid] method may be used to assert that a response does not have validation errors that were returned as JSON and that no errors were flashed to session storage.

assertJsonPathassertJsonPath

レスポンスに、指定するパスの指定するデータが含まれていることを宣言します。Assert that the response contains the given data at the specified path:

$response->assertJsonPath($path, $expectedValue);

たとえば、アプリケーションが返すJSONレスポンスに次のデータが含まれている場合:For example, if the JSON response returned by your application contains the following data:

{
    "user": {
        "name": "Steve Schoger"
    }
}

userオブジェクトのnameプロパティが次のように指定する値に一致すると宣言することができます。You may assert that the name property of the user object matches a given value like so:

$response->assertJsonPath('user.name', 'Steve Schoger');

assertJsonStructureassertJsonStructure

レスポンスが指定のJSON構造を持っていることを宣言します。Assert that the response has a given JSON structure:

$response->assertJsonStructure(array $structure);

たとえば、アプリケーションが返すJSONレスポンスに次のデータが含まれている場合:For example, if the JSON response returned by your application contains the following data:

{
    "user": {
        "name": "Steve Schoger"
    }
}

次のように、JSON構造がエクスペクテーションに一致すると宣言できます。You may assert that the JSON structure matches your expectations like so:

$response->assertJsonStructure([
    'user' => [
        'name',
    ]
]);

時々、アプリケーションが返すJSONレスポンスには、オブジェクトの配列が含まれている可能性があります。Sometimes, JSON responses returned by your application may contain arrays of objects:

{
    "user": [
        {
            "name": "Steve Schoger",
            "age": 55,
            "location": "Earth"
        },
        {
            "name": "Mary Schoger",
            "age": 60,
            "location": "Earth"
        }
    ]
}

この状況では、*文字を使って配列内のすべてのオブジェクトの構造に対して宣言できます。In this situation, you may use the * character to assert against the structure of all of the objects in the array:

$response->assertJsonStructure([
    'user' => [
        '*' => [
             'name',
             'age',
             'location'
        ]
    ]
]);

assertJsonValidationErrorsassertJsonValidationErrors

レスポンスへ、指定するキーに対する指定するJSONバリデーションエラーがあることを宣言します。このメソッドは、バリデーションエラーがセッションに一時保存されているのではなく、バリデーションエラーをJSON構造として返すレスポンスに対して宣言する場合に使用する必要があります。Assert that the response has the given JSON validation errors for the given keys. This method should be used when asserting against responses where the validation errors are returned as a JSON structure instead of being flashed to the session:

$response->assertJsonValidationErrors(array $data, $responseKey = 'errors');

lightbulb">Tip!! より一般的なassertInvalidメソッドを使用して、JSONで返されたレスポンスにバリデーションエラーが存在した、もしくはエラーがセッションストレージに一時保存されたことを宣言できます。{tip} The more generic assertInvalid[#assert-invalid] method may be used to assert that a response has validation errors returned as JSON or that errors were flashed to session storage.

assertJsonValidationErrorForassertJsonValidationErrorFor

レスポンスが指定キーに対するJSONバリデーションエラーを持っていることを宣言します。Assert the response has any JSON validation errors for the given key:

$response->assertJsonValidationErrorFor(string $key, $responseKey = 'errors');

assertLocationassertLocation

レスポンスのLocationヘッダに指定するURI値があることを宣言します。Assert that the response has the given URI value in the Location header:

$response->assertLocation($uri);

assertNoContentassertNoContent

レスポンスに指定するHTTPステータスコードがあり、コンテンツがないことを宣言します。Assert that the response has the given HTTP status code and no content:

$response->assertNoContent($status = 204);

assertNotFoundassertNotFound

レスポンスにNot Found(404)HTTPステータスコードがあることを宣言します。Assert that the response has a not found (404) HTTP status code:

$response->assertNotFound();

assertOkassertOk

レスポンスに200 HTTPステータスコードがあることを宣言します。Assert that the response has a 200 HTTP status code:

$response->assertOk();

assertPlainCookieassertPlainCookie

レスポンスに指定する暗号化されていないクッキーが含まれていることを宣言します。Assert that the response contains the given unencrypted cookie:

$response->assertPlainCookie($cookieName, $value = null);

assertRedirectassertRedirect

レスポンスが指定するURIへのリダイレクトであることを宣言します。Assert that the response is a redirect to the given URI:

$response->assertRedirect($uri);

assertRedirectContainsassertRedirectContains

レスポンスが指定文字列を含むURIへリダイレクトされることを宣言する。Assert whether the response is redirecting to a URI that contains the given string:

$response->assertRedirectContains($string);

assertRedirectToSignedRouteassertRedirectToSignedRoute

レスポンスが指定する著名付きルートへのリダイレクトであることを宣言します。Assert that the response is a redirect to the given signed route:

$response->assertRedirectToSignedRoute($name = null, $parameters = []);

assertSeeassertSee

指定する文字列がレスポンスに含まれていることを宣言します。このアサートは、2番目の引数にfalseを渡さない限り、指定する文字列を自動的にエスケープします。Assert that the given string is contained within the response. This assertion will automatically escape the given string unless you pass a second argument of false:

$response->assertSee($value, $escaped = true);

assertSeeInOrderassertSeeInOrder

指定する文字列がレスポンス内に順番に含まれていることを宣言します。このアサートは、2番目の引数へfalseを渡さない限り、指定する文字列を自動的にエスケープします。Assert that the given strings are contained in order within the response. This assertion will automatically escape the given strings unless you pass a second argument of false:

$response->assertSeeInOrder(array $values, $escaped = true);

assertSeeTextassertSeeText

指定する文字列がレスポンステキストに含まれていることを宣言します。このアサートは、2番目の引数にfalseを渡さない限り、指定する文字列を自動的にエスケープします。アサートが作成される前に、レスポンスの内容がstrip_tagsPHP関数に渡されます。Assert that the given string is contained within the response text. This assertion will automatically escape the given string unless you pass a second argument of false. The response content will be passed to the strip_tags PHP function before the assertion is made:

$response->assertSeeText($value, $escaped = true);

assertSeeTextInOrderassertSeeTextInOrder

指定する文字列がレスポンステキスト内に順番に含まれていることを宣言します。このアサートは、2番目の引数にfalseを渡さない限り、指定する文字列を自動的にエスケープします。アサートが作成される前に、レスポンスの内容がstrip_tagsPHP関数に渡されます。Assert that the given strings are contained in order within the response text. This assertion will automatically escape the given strings unless you pass a second argument of false. The response content will be passed to the strip_tags PHP function before the assertion is made:

$response->assertSeeTextInOrder(array $values, $escaped = true);

assertSessionHasassertSessionHas

セッションに指定するデータが含まれていることを宣言します。Assert that the session contains the given piece of data:

$response->assertSessionHas($key, $value = null);

必要であれば、クロージャをassertSessionHasメソッドの第2引数へ指定できます。クロージャがtrueを返せば、アサートは成功します。If needed, a closure can be provided as the second argument to the assertSessionHas method. The assertion will pass if the closure returns true:

$response->assertSessionHas($key, function ($value) {
    return $value->name === 'Taylor Otwell';
});

assertSessionHasInputassertSessionHasInput

セッションの一時保存されている入力配列に指定する値があることを宣言します。Assert that the session has a given value in the flashed input array[/docs/{{version}}/responses#redirecting-with-flashed-session-data]:

$response->assertSessionHasInput($key, $value = null);

必要であれば、クロージャをassertSessionHasInputメソッドの第2引数へ指定できます。クロージャがtrueを返せば、アサートは成功します。If needed, a closure can be provided as the second argument to the assertSessionHasInput method. The assertion will pass if the closure returns true:

$response->assertSessionHasInput($key, function ($value) {
    return Crypt::decryptString($value) === 'secret';
});

assertSessionHasAllassertSessionHasAll

セッションにキー/値ペアの指定配列が含まれていることを宣言します。Assert that the session contains a given array of key / value pairs:

$response->assertSessionHasAll(array $data);

たとえば、アプリケーションのセッションにnameキーとstatusキーが含まれている場合、両方が存在し、以下のような指定値を持っていると宣言できます。For example, if your application's session contains name and status keys, you may assert that both exist and have the specified values like so:

$response->assertSessionHasAll([
    'name' => 'Taylor Otwell',
    'status' => 'active',
]);

assertSessionHasErrorsassertSessionHasErrors

指定する$keysのエラーがセッションに含まれていることを宣言します。$keysが連想配列の場合、セッションに各フィールド(キー)の特定のエラーメッセージ(値)が含まれていることを宣言します。このメソッドは、バリデーションエラーをJSON構造として返すのではなく、セッションに一時保存するルートをテストするときに使用する必要があります。Assert that the session contains an error for the given $keys. If $keys is an associative array, assert that the session contains a specific error message (value) for each field (key). This method should be used when testing routes that flash validation errors to the session instead of returning them as a JSON structure:

$response->assertSessionHasErrors(
    array $keys, $format = null, $errorBag = 'default'
);

たとえば、nameフィールドとemailフィールドにセッションへ一時保存された検証エラーメッセージがあることを宣言するには、以下のようにassertSessionHasErrorsメソッドを呼び出すことができます。For example, to assert that the name and email fields have validation error messages that were flashed to the session, you may invoke the assertSessionHasErrors method like so:

$response->assertSessionHasErrors(['name', 'email']);

または、特定のフィールドに特定のバリデーションエラーメッセージがあると宣言することもできます。Or, you may assert that a given field has a particular validation error message:

$response->assertSessionHasErrors([
    'name' => 'The given name was invalid.'
]);

assertSessionHasErrorsInassertSessionHasErrorsIn

指定エラーバッグ内に指定する$keysのエラーがセッションに含まれていることを宣言します。$keysが連想配列の場合、セッションにはエラーバッグ内の各フィールド(キー)に特定のエラーメッセージ(値)が含まれていることを宣言します。Assert that the session contains an error for the given $keys within a specific error bag[/docs/{{version}}/validation#named-error-bags]. If $keys is an associative array, assert that the session contains a specific error message (value) for each field (key), within the error bag:

$response->assertSessionHasErrorsIn($errorBag, $keys = [], $format = null);

assertSessionHasNoErrorsassertSessionHasNoErrors

セッションにバリデーションエラーがないことを宣言します。Assert that the session has no validation errors:

$response->assertSessionHasNoErrors();

assertSessionDoesntHaveErrorsassertSessionDoesntHaveErrors

指定するキーのバリデーションエラーがセッションにないことを宣言します。Assert that the session has no validation errors for the given keys:

$response->assertSessionDoesntHaveErrors($keys = [], $format = null, $errorBag = 'default');

assertSessionMissingassertSessionMissing

セッションに指定するキーが含まれていないことを宣言します。Assert that the session does not contain the given key:

$response->assertSessionMissing($key);

assertStatusassertStatus

レスポンスに指定HTTPステータスコードがあることを宣言します。Assert that the response has a given HTTP status code:

$response->assertStatus($code);

assertSuccessfulassertSuccessful

レスポンスに成功した(>=200および<300)HTTPステータスコードがあることを宣言します。Assert that the response has a successful (>= 200 and < 300) HTTP status code:

$response->assertSuccessful();

assertUnauthorizedassertUnauthorized

レスポンスに不正な(401)HTTPステータスコードがあることを宣言します。Assert that the response has an unauthorized (401) HTTP status code:

$response->assertUnauthorized();

assertUnprocessableassertUnprocessable

レスポンスに未処理のエンティティ(422)HTTPステータスコードがあることを宣言します。Assert that the response has an unprocessable entity (422) HTTP status code:

$response->assertUnprocessable();

assertValidassertValid

レスポンスに指定キーのバリデーションエラーがないことを宣言します。このメソッドは、バリデーションエラーをJSON構造として返す、もしくはバリデーションエラーをセッションへ一時保存しているレスポンスに対する宣言に使用します。Assert that the response has no validation errors for the given keys. This method may be used for asserting against responses where the validation errors are returned as a JSON structure or where the validation errors have been flashed to the session:

// バリデーションエラーが発生していないことを宣言
$response->assertValid();

// 指定キーのバリデーションエラーがないことを宣言
$response->assertValid(['name', 'email']);

assertInvalidassertInvalid

レスポンスに指定キーのバリデーションエラーがあることを宣言します。このメソッドは、バリデーションエラーをJSON構造として返す、もしくはバリデーションエラーをセッションへ一時保存しているレスポンスに対する宣言に使用します。Assert that the response has validation errors for the given keys. This method may be used for asserting against responses where the validation errors are returned as a JSON structure or where the validation errors have been flashed to the session:

$response->assertInvalid(['name', 'email']);

特定のキーに特定のバリデーションエラーメッセージがあることを宣言することもできます。その場合、メッセージ全体またはメッセージのごく一部だけを指定できます。You may also assert that a given key has a particular validation error message. When doing so, you may provide the entire message or only a small portion of the message:

$response->assertInvalid([
    'name' => 'The name field is required.',
    'email' => 'valid email address',
]);

assertViewHasassertViewHas

指定するデータの部分がレスポンスビューに含まれていることを宣言します。Assert that the response view contains given a piece of data:

$response->assertViewHas($key, $value = null);

assertViewHasメソッドの2番目の引数にクロージャを渡すと、ビューデータの特定部分に対して検査し、アサートできます。Passing a closure as the second argument to the assertViewHas method will allow you to inspect and make assertions against a particular piece of view data:

$response->assertViewHas('user', function (User $user) {
    return $user->name === 'Taylor';
});

さらに、ビューデータはレスポンスの配列変数としてアクセスできるため、次のように簡単に検査できます。In addition, view data may be accessed as array variables on the response, allowing you to conveniently inspect it:

$this->assertEquals('Taylor', $response['name']);

assertViewHasAllassertViewHasAll

レスポンスビューに指定するデータのリストがあることを宣言します。Assert that the response view has a given list of data:

$response->assertViewHasAll(array $data);

このメソッドは、ビューに指定するキーに一致するデータが含まれていることを宣言するために使用できます。This method may be used to assert that the view simply contains data matching the given keys:

$response->assertViewHasAll([
    'name',
    'email',
]);

または、ビューデータが存在し、特定の値を持っていると宣言することもできます。Or, you may assert that the view data is present and has specific values:

$response->assertViewHasAll([
    'name' => 'Taylor Otwell',
    'email' => 'taylor@example.com,',
]);

assertViewIsassertViewIs

指定するビューがルートによって返されたことを宣言します。Assert that the given view was returned by the route:

$response->assertViewIs($value);

assertViewMissingassertViewMissing

指定するデータキーが、アプリケーションのレスポンスで返されたビューで使用可能になっていないことを宣言します。Assert that the given data key was not made available to the view returned in the application's response:

$response->assertViewMissing($key);

認証のアサートAuthentication Assertions

Laravelは、アプリケーションの機能テストで利用できるさまざまな認証関連のアサートも提供します。これらのメソッドは、getpostなどのメソッドによって返されるIlluminate\Testing\TestResponseインスタンスではなく、テストクラス自体で呼び出されることに注意してください。Laravel also provides a variety of authentication related assertions that you may utilize within your application's feature tests. Note that these methods are invoked on the test class itself and not the Illuminate\Testing\TestResponse instance returned by methods such as get and post.

assertAuthenticatedassertAuthenticated

ユーザーが認証済みであることを宣言します。Assert that a user is authenticated:

$this->assertAuthenticated($guard = null);

assertGuestassertGuest

ユーザーが認証されていないことを宣言します。Assert that a user is not authenticated:

$this->assertGuest($guard = null);

assertAuthenticatedAsassertAuthenticatedAs

特定のユーザーが認証済みであることを宣言します。Assert that a specific user is authenticated:

$this->assertAuthenticatedAs($user, $guard = null);

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作