Readouble

Laravel master アプリケーションテスト

イントロダクションIntroduction

Laravelはアプリケーションに送るHTTPリクエストの作成、出力の検査、さらにフォームの入力もスラスラと書けるAPIを提供しています。例として、次に定義するテストを見てください。Laravel provides a very fluent API for making HTTP requests to your application, examining the output, and even filling out forms. For example, take a look at the test defined below:

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    /**
     * 基本的な機能テストの例
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->visit('/')
             ->see('Laravel 5')
             ->dontSee('Rails');
    }
}

visitメソッドは、アプリケーションに対するGETリクエストを作成します。seeメソッドは指定されたテキストが、アプリケーションから返されるレスポンスの中に存在することをアサートします。dontSeeメソッドは指定したテキストが、アプリケーションレスポンスの中へ返されていないことをアサートします。これはLaravelで使用できる最も基本的なアプリケーションテストです。The visit method makes a GET request into the application. The see method asserts that we should see the given text in the response returned by the application. The dontSee method asserts that the given text is not returned in the application response. This is the most basic application test available in Laravel.

ルートに付けられた名前を使い、GETリクエストを作るvisitRouteメソッドも使用可能です。You may also use the 'visitRoute' method to make a 'GET' request via a named route:

$this->visitRoute('profile');

$this->visitRoute('profile', ['user' => 1]);

アプリケーションのテストInteracting With Your Application

もちろんシンプルに指定したレスポンスの中にテキストが現れるかアサートする以上のことが可能です。リンクのクリックとフォームの埋め込みを見てみましょう。Of course, you can do much more than simply assert that text appears in a given response. Let's take a look at some examples of clicking links and filling out forms:

リンクのテストInteracting With Links

このテストではアプリケーションへのリクエストを作成し、帰ってきたレスポンス中のリンクを「クリック」、それから指定されたURIに到達することをアサートします。たとえば"About Us"のテキスト値を持つレスポンスの中のリンクがあると仮定しましょう。In this test, we will make a request to the application, "click" a link in the returned response, and then assert that we landed on a given URI. For example, let's assume there is a link in our response that has a text value of "About Us":

<a href="/about-us">About Us</a>

では、このリンクをクリックし、正しいページに到達したことをアサートしましょう。Now, let's write a test that clicks the link and asserts the user lands on the correct page:

public function testBasicExample()
{
    $this->visit('/')
         ->click('About Us')
         ->seePageIs('/about-us');
}

ユーザが正しい名前付きルートへ到達することを確認する、seeRouteIsメソッドも使用できます。You may also check that the user has arrived at the correct named route using the seeRouteIs method:

->seeRouteIs('profile', ['user' => 1]);

フォームのテストInteracting With Forms

Laravelはさらにフォームをテストするために多くのメソッドを提供しています。typeselectcheckattachpressメソッドはフォーム入力の全てを操作させてくれます。たとえば、アプリケーションの登録ページにこのフォームがあると考えてください。Laravel also provides several methods for testing forms. The type, select, check, attach, and press methods allow you to interact with all of your form's inputs. For example, let's imagine this form exists on the application's registration page:

<form action="/register" method="POST">
    {{ csrf_field() }}

    <div>
        Name: <input type="text" name="name">
    </div>

    <div>
        <input type="checkbox" value="yes" name="terms"> Accept Terms
    </div>

    <div>
        <input type="submit" value="Register">
    </div>
</form>

このフォームを完全に埋め、結果を確認するテストが書けます。We can write a test to complete this form and inspect the result:

public function testNewUserRegistration()
{
    $this->visit('/register')
         ->type('Taylor', 'name')
         ->check('terms')
         ->press('Register')
         ->seePageIs('/dashboard');
}

もちろん、フォームにラジオボタンやドロップボックスのような他の入力が含まれていても、同様にそうしたフィールドを簡単に埋めることができます。フォーム操作メソッドのリストを見てください。Of course, if your form contains other inputs such as radio buttons or drop-down boxes, you may easily fill out those types of fields as well. Here is a list of each form manipulation method:

メソッドMethod 説明Description
$this->type($text, $elementName)$this->type($text, $elementName) 指定したフィールドに「タイプ」します。"Type" text into a given field.
$this->select($value, $elementName)$this->select($value, $elementName) ラジオボタンかドロップダウンフィールドを「選択」します。"Select" a radio button or drop-down field.
$this->check($elementName)$this->check($elementName) チェックボックスフィールドを「チェック」します。"Check" a checkbox field.
$this->uncheck($elementName)$this->uncheck($elementName) チェックボックスフィールドを「非チェック」にします。"Uncheck" a checkbox field.
$this->attach($pathToFile, $elementName)$this->attach($pathToFile, $elementName) フォームにファイルを「添付」します。"Attach" a file to the form.
$this->press($buttonTextOrElementName)$this->press($buttonTextOrElementName) 指定したテキストか名前のボタンを「押し」ます。"Press" a button with the given text or name.

ファイル入力File Inputs

フォームにfile入力タイプが含まれているならば、attachメソッドを使いフォームにファイルを添付できます。If your form contains file inputs, you may attach files to the form using the attach method:

public function testPhotoCanBeUploaded()
{
    $this->visit('/upload')
         ->attach($pathToFile, 'photo')
         ->press('Upload')
         ->see('Upload Successful!');
}

JSON APIのテストTesting JSON APIs

さらにLaravelは、JSON APIとそれらのレスポンスをテストするために、多くのヘルパも用意しています。たとえば、jsongetpostputpatchdeleteメソッドは各HTTP動詞でのリクエストを発行するために使用します。また簡単にデータとヘッダをメソッドに渡すこともできます。手始めに、/userに対するPOSTリクエストを作成し、期待したデータが返ってくることをアサートするテストを書いてみましょう。Laravel also provides several helpers for testing JSON APIs and their responses. For example, the json, get, post, put, patch, and delete methods may be used to issue 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 /user and assert that the expected data was returned:

<?php

class ExampleTest extends TestCase
{
    /**
     * 基本的な機能テストの例
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->json('POST', '/user', ['name' => 'Sally'])
             ->seeJson([
                 'created' => true,
             ]);
    }
}

lightbulb">Tip!! seeJsonメソッドは渡された配列をJSONに変換します。次にそのJSONが、JSONレスポンス全体のいずれかに現れるかを確認します。ですから、他のプロパティーがJSONレスポンスに含まれていたとしても、指定した部分が存在する限り、テストはパスします。{tip} The seeJson method converts the given array into JSON, and then verifies that the JSON fragment occurs anywhere within the entire 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.

厳格な一致の確認Verifying Exact Match

指定した配列がアプリケーションから返されるJSONと厳格に一致するかを確認したい場合は、seeJsonEqualsメソッドを使用してください。If you would like to verify that the given array is an exact match for the JSON returned by the application, you should use the seeJsonEquals method:

<?php

class ExampleTest extends TestCase
{
    /**
     * 基本的な機能テストの例
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->json('POST', '/user', ['name' => 'Sally'])
             ->seeJsonEquals([
                 'created' => true,
             ]);
    }
}

構造の一致の確認Verifying Structural Match

JSON形式が特定の構造にピタリと当てはまるかを確認することもできます。このシナリオでは、期待するJSON構造をseeJsonStructureメソッドに渡してください。It is also possible to verify that a JSON response adheres to a specific structure. In this scenario, you should use the seeJsonStructure method and pass it your expected JSON structure:

<?php

class ExampleTest extends TestCase
{
    /**
     * 基本的な機能テストの例
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->get('/user/1')
             ->seeJsonStructure([
                 'name',
                 'pet' => [
                     'name', 'age'
                 ]
             ]);
    }
}

上の例ではnameおよび、nameageを持つネストしたpetオブジェクトを受け取ることを期待しています。seeJsonStructureは、レスポンスが余計なキーを含んていても失敗しません。たとえば、petweight属性を持っていても、テストをパスします。The above example illustrates an expectation of receiving a name attribute and a nested pet object with its own name and age attributes. seeJsonStructure will not fail if additional keys are present in the response. For example, the test would still pass if the pet had a weight attribute.

*を使い、戻ってきたJSON構造がリストを持っていること、そして各リストが最低でも持っている属性を指定することもできます。You may use the * to assert that the returned JSON structure has a list where each list item contains at least the attributes found in the set of values:

<?php

class ExampleTest extends TestCase
{
    /**
     * 基本的な機能テストの例
     *
     * @return void
     */
    public function testBasicExample()
    {
        // リスト中の各ユーザが、最低でもid、name、email属性を持っていることをアサートする
        $this->get('/users')
             ->seeJsonStructure([
                 '*' => [
                     'id', 'name', 'email'
                 ]
             ]);
    }
}

*記述法はネストもできます。次の例の場合、JSONレスポンスの各ユーザは指定されている属性を持っており、各ユーザの各ペットも指定されている属性を持っていることを宣言します。You may also nest the * notation. In this case, we will assert that each user in the JSON response contains a given set of attributes and that each pet on each user also contains a given set of attributes:

$this->get('/users')
     ->seeJsonStructure([
         '*' => [
             'id', 'name', 'email', 'pets' => [
                 '*' => [
                     'name', 'age'
                 ]
             ]
         ]
     ]);

セッション/認証Sessions / Authentication

Laravelはテスト時にセッションを操作するたくさんのヘルパも提供しています。1つ目は指定した配列をセッションに保存するwithSessionメソッドです。これはアプリケーションのリクエストをテストする前に、データをセッションにロードしたい場合に便利です。Laravel provides several helpers for working with the session during 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

class ExampleTest extends TestCase
{
    public function testApplication()
    {
        $this->withSession(['foo' => 'bar'])
             ->visit('/');
    }
}

もちろん認証済みのユーザのようなユーザ状態をセッションへ保持するのは一般的です。actingAsヘルパメソッドは現在認証済みのユーザを指定する簡単な手段を提供します。たとえば、モデルファクトリでユーザを生成し、認証してみましょう。Of course, one common use of the session is for maintaining state for the authenticated user. 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#model-factories] to generate and authenticate a user:

<?php

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

        $this->actingAs($user)
             ->withSession(['foo' => 'bar'])
             ->visit('/')
             ->see('Hello, '.$user->name);
    }
}

ユーザの認証にどのガードを使用するかを指定したい場合、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, 'api')

ミドルウェアの無効化Disabling Middleware

アプリケーションをテストするとき、いくつかのテストではミドルウェアを無効にするほうが便利だと気がつくでしょう。これによりミドルウェアに関わらずにルートやコントローラーのテストが可能になります。LaravelはシンプルなWithoutMiddlewareトレイトを用意しており、これを使えば自動的にテストクラスのミドルウェアを無効にできます。When testing your application, you may find it convenient to disable middleware[/docs/{{version}}/middleware] for some of your tests. This will allow you to test your routes and controller in isolation from any middleware concerns. Laravel includes a simple WithoutMiddleware trait that you can use to automatically disable all middleware for the test class:

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    use WithoutMiddleware;

    //
}

いくつかのテストメソッドだけでミドルウェアを無効にしたい場合は、withoutMiddlewareメソッドをテストメソッドの中で呼び出してください。If you would like to only disable middleware for a few test methods, you may call the withoutMiddleware method from within the test methods:

<?php

class ExampleTest extends TestCase
{
    /**
     * 基本的な機能テストの例
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->withoutMiddleware();

        $this->visit('/')
             ->see('Laravel 5');
    }
}

カスタムHTTPリクエストCustom HTTP Requests

アプリケーションに対してカスタムHTTPリクエストを作成し、完全なIlluminate\Http\Responseオブジェクトを取得したい場合は、callメソッドを使ってください。If you would like to make a custom HTTP request into your application and get the full Illuminate\Http\Response object, you may use the call method:

public function testApplication()
{
    $response = $this->call('GET', '/');

    $this->assertEquals(200, $response->status());
}

POSTPUTPATCHリクエストの場合、そのリクエストに入力データの配列を渡すことができます。もちろん、このデーターはRequestインスタンスを使用し、ルートやコントローラーで使用できます。If you are making POST, PUT, or PATCH requests you may pass an array of input data with the request. Of course, this data will be available in your routes and controller via the Request instance[/docs/{{version}}/requests]:

   $response = $this->call('POST', '/user', ['name' => 'Taylor']);

PHPUnitアサートPHPUnit Assertions

PHPUnitテスト用に、数多くの追加アサートメソッドをLaravelは提供しています。Laravel provides a variety of custom assertion methods for PHPUnit[https://phpunit.de/] tests:

メソッドMethod 説明Description
->assertResponseOk();->assertResponseOk(); クライアントのレスポンスがOKのステータスコードを受け取ることを宣言Assert that the client response has an OK status code.
->assertResponseStatus($code);->assertResponseStatus($code); クライアントのレスポンスが指定したコードであることを宣言Assert that the client response has a given code.
->assertViewHas($key, $value = null);->assertViewHas($key, $value = null); レスポンスのビューに指定したデータが含まれていることを宣言Assert that the response view has a given piece of bound data.
->assertViewHasAll(array $bindings);->assertViewHasAll(array $bindings); ビューが指定したデータのリストを持っていることを宣言Assert that the view has a given list of bound data.
->assertViewMissing($key);->assertViewMissing($key); ビューが指定したデータを含んでいないことを宣言Assert that the response view is missing a piece of bound data.
->assertRedirectedTo($uri, $with = []);->assertRedirectedTo($uri, $with = []); クライアントが指定したURIへリダイレクトすることを宣言Assert whether the client was redirected to a given URI.
->assertRedirectedToRoute($name, $parameters = [], $with = []);->assertRedirectedToRoute($name, $parameters = [], $with = []); クライアントが指定したルートへリダイレクトされることを宣言Assert whether the client was redirected to a given route.
->assertRedirectedToAction($name, $parameters = [], $with = []);->assertRedirectedToAction($name, $parameters = [], $with = []); クライアントが指定したアクションへリダイレクトすることを宣言Assert whether the client was redirected to a given action.
->assertSessionHas($key, $value = null);->assertSessionHas($key, $value = null); セッションが指定した値を持つことを宣言Assert that the session has a given value.
->assertSessionHasAll(array $bindings);->assertSessionHasAll(array $bindings); セッションが指定したリストを持つことを宣言Assert that the session has a given list of values.
->assertSessionHasErrors($bindings = [], $format = null);->assertSessionHasErrors($bindings = [], $format = null); セッションにエラー情報があることを宣言Assert that the session has errors bound.
->assertHasOldInput();->assertHasOldInput(); セッションが直前の入力を持つことを宣言Assert that the session has old input.
->assertSessionMissing($key);->assertSessionMissing($key); セッションが指定したキーを持っていないことを宣言Assert that the session is missing a given key.

章選択

開発環境
ビューとテンプレート
公式パッケージ

設定

明暗テーマ
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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作