Readouble

Laravel 5.8 データベースのテスト

イントロダクションIntroduction

Laravelでは、データベースを駆動するアプリケーションのテストを簡単にできる、便利で様々なツールを用意しています。その一つは、指定した抽出条件に一致するデータがデータベース中に存在するかをアサートする、assertDatabaseHasヘルパです。たとえば、usersテーブルの中にemailフィールドがsally@example.comの値のレコードが存在するかを確認したいとしましょう。次のようにテストできます。Laravel provides a variety of helpful tools to make it easier to test your database driven applications. First, you may use the assertDatabaseHas helper to assert that data exists in the database matching a given set of criteria. For example, if you would like to verify that there is a record in the users table with the email value of sally@example.com, you can do the following:

public function testDatabase()
{
    // アプリケーションを呼び出す…

    $this->assertDatabaseHas('users', [
        'email' => 'sally@example.com'
    ]);
}

データベースにデータが存在しないことをアサートする、assertDatabaseMissingヘルパを使うこともできます。You can also use the assertDatabaseMissing helper to assert that data does not exist in the database.

assertDatabaseHasメソッドやその他のヘルパは、皆さんが便利に使ってもらうため用意しています。PHPUnitの組み込みアサートメソッドは、テストで自由に使用できます。The assertDatabaseHas method and other helpers like it are for convenience. You are free to use any of PHPUnit's built-in assertion methods to supplement your tests.

ファクトリの生成Generating Factories

ファクトリを生成するには、make:factory Artisanコマンドを使用します。To create a factory, use the make:factory Artisan command[/docs/{{version}}/artisan]:

php artisan make:factory PostFactory

新しいファクトリは、database/factoriesディレクトリに設置されます。The new factory will be placed in your database/factories directory.

--modelオプションにより、ファクトリが生成するモデルの名前を指定できます。このオプションは、生成するファクトリファイルへ指定モデル名を事前に設定します。The --model option may be used to indicate the name of the model created by the factory. This option will pre-fill the generated factory file with the given model:

php artisan make:factory PostFactory --model=Post

各テスト後のデータベースリセットResetting The Database After Each Test

前のテストがその後のテストデータに影響しないように、各テストの後にデータベースをリセットできると便利です。インメモリデータベースを使っていても、トラディショナルなデータベースを使用していても、RefreshDatabaseトレイトにより、マイグレーションに最適なアプローチが取れます。テストクラスにてこのトレイトを使えば、全てが処理されます。It is often useful to reset your database after each test so that data from a previous test does not interfere with subsequent tests. The RefreshDatabase trait takes the most optimal approach to migrating your test database depending on if you are using an in-memory database or a traditional database. Use the trait on your test class and everything will be handled for you:

<?php

namespace Tests\Feature;

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

class ExampleTest extends TestCase
{
    use RefreshDatabase;

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

        // ...
    }
}

ファクトリの記述Writing Factories

テスト実行前に、何件かのレコードをデータベースに挿入する必要があります。こうしたテストデータを作る時に、手動でそれぞれのカラムへ値を指定する代わりに、Laravelではモデルファクトリを使用し、Eloquentモデルの各属性にデフォルト値を設定できます。手始めに、アプリケーションのdatabase/factories/UserFactory.phpファイルを見てください。このファイルには初めからファクトリの定義が一つ含まれています。When testing, you may need to insert a few records into your database before executing your test. Instead of manually specifying the value of each column when you create this test data, Laravel allows you to define a default set of attributes for each of your Eloquent models[/docs/{{version}}/eloquent] using model factories. To get started, take a look at the database/factories/UserFactory.php file in your application. Out of the box, this file contains one factory definition:

use Illuminate\Support\Str;
use Faker\Generator as Faker;

$factory->define(App\User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
        'remember_token' => Str::random(10),
    ];
});

ファクトリで定義しているクロージャの中から、モデルの全属性に対するデフォルトのテスト値を返しています。このクロージャはFaker PHPライブラリーのインスタンスを受け取っており、これはテストのための多用なランダムデータを生成するのに便利です。Within the Closure, which serves as the factory definition, you may return the default test values of all attributes on the model. The Closure will receive an instance of the Faker[https://github.com/fzaninotto/Faker] PHP library, which allows you to conveniently generate various kinds of random data for testing.

より組織立てるために、各モデルごとに追加のファクトリファイルを作成することもできます。たとえば、database/factoriesディレクトリにUserFactory.phpCommentFactory.phpファイルを作成できます。factoriesディレクトリ下の全ファイルは、Laravelにより自動的にロードされます。You may also create additional factory files for each model for better organization. For example, you could create UserFactory.php and CommentFactory.php files within your database/factories directory. All of the files within the factories directory will automatically be loaded by Laravel.

lightbulb">Tip!! Fakerのローケルは、config/app.php設定ファイルのfaker_localeオプションで指定できます。{tip} You can set the Faker locale by adding a faker_locale option to your config/app.php configuration file.

ファクトリステートFactory States

ステートにより、モデルファクトリのどんな組み合わせに対しても適用できる、個別の調整を定義できます。たとえば、Userモデルは、デフォルト属性値の一つを変更する、delinquentステートを持つとしましょう。stateメソッドを使い、状態変換を定義します。単純なステートでは、属性の変換の配列を渡します。States allow you to define discrete modifications that can be applied to your model factories in any combination. For example, your User model might have a delinquent state that modifies one of its default attribute values. You may define your state transformations using the state method. For simple states, you may pass an array of attribute modifications:

$factory->state(App\User::class, 'delinquent', [
    'account_status' => 'delinquent',
]);

ステートで計算や$fakerインスタンスが必要な場合は、ステートの属性変換を計算するために、クロージャを使います。If your state requires calculation or a $faker instance, you may use a Closure to calculate the state's attribute modifications:

$factory->state(App\User::class, 'address', function ($faker) {
    return [
        'address' => $faker->address,
    ];
});

ファクトリコールバックFactory Callbacks

ファクトリコールバックはafterMakingafterCreatingメソッドを使用し登録し、モデルを作成、もしくは生成した後の追加タスクを実行できるようにします。例として、生成したモデルに追加のモデルを関係づけるコールバックを利用してみましょう。Factory callbacks are registered using the afterMaking and afterCreating methods, and allow you to perform additional tasks after making or creating a model. For example, you may use callbacks to relate additional models to the created model:

$factory->afterMaking(App\User::class, function ($user, $faker) {
    // ...
});

$factory->afterCreating(App\User::class, function ($user, $faker) {
    $user->accounts()->save(factory(App\Account::class)->make());
});

ファクトリステートのために、コールバックを定義することも可能です。You may also define callbacks for factory states[#factory-states]:

$factory->afterMakingState(App\User::class, 'delinquent', function ($user, $faker) {
    // ...
});

$factory->afterCreatingState(App\User::class, 'delinquent', function ($user, $faker) {
    // ...
});

ファクトリの使用Using Factories

モデルの生成Creating Models

ファクトリを定義し終えたら、テストかデータベースのシーディング(初期値設定)ファイルの中で、グローバルなfactory関数を使用してモデルインスタンスを生成できます。では、モデル生成の例をいくつか見てみましょう。最初はmakeメソッドでモデルを生成し、データベースには保存しない方法です。Once you have defined your factories, you may use the global factory function in your tests or seed files to generate model instances. So, let's take a look at a few examples of creating models. First, we'll use the make method to create models but not save them to the database:

public function testDatabase()
{
    $user = factory(App\User::class)->make();

    // モデルをテストで使用…
}

さらにモデルのコレクションや指定したタイプのモデルも生成できます。You may also create a Collection of many models or create models of a given type:

// App\Userインスタンスを3つ生成
$users = factory(App\User::class, 'admin', 3)->make();

ステートの適用Applying States

こうしたモデルに対してステートを適用することもできます。複数の状態遷移を適用したい場合は、それぞれの適用対象のステート名を指定します。You may also apply any of your states[#factory-states] to the models. If you would like to apply multiple state transformations to the models, you should specify the name of each state you would like to apply:

$users = factory(App\User::class, 5)->states('delinquent')->make();

$users = factory(App\User::class, 5)->states('premium', 'delinquent')->make();

属性のオーバーライドOverriding Attributes

モデルのデフォルト値をオーバーライドしたい場合は、makeメソッドに配列で値を渡してください。指定した値のみ置き換わり、残りの値はファクトリで指定したデフォルト値のまま残ります。If you would like to override some of the default values of your models, you may pass an array of values to the make method. Only the specified values will be replaced while the rest of the values remain set to their default values as specified by the factory:

$user = factory(App\User::class)->make([
    'name' => 'Abigail',
]);

lightbulb">Tip!! ファクトリを用いモデルを生成する場合は、複数代入の保護を自動的に無効にします。{tip} Mass assignment protection[/docs/{{version}}/eloquent#mass-assignment] is automatically disabled when creating models using factories.

モデルの保存Persisting Models

createメソッドはモデルインスタンスを生成するだけでなく、Eloquentのsaveメソッドを使用しデータベースへ保存します。The create method not only creates the model instances but also saves them to the database using Eloquent's save method:

public function testDatabase()
{
    // 一つのApp\Userインスタンスを作成
    $user = factory(App\User::class)->create();

    // App\Userインスタンスを3つ生成
    $users = factory(App\User::class, 3)->create();

    // モデルをテストで使用…
}

createメソッドに配列で値を渡すことで、モデルの属性をオーバーライドできます。You may override attributes on the model by passing an array to the create method:

$user = factory(App\User::class)->create([
    'name' => 'Abigail',
]);

リレーションRelationships

以下の例では、生成したモデルにリレーションを付けています。複数モデルの生成にcreateメソッドを使用する場合、インスタンスのコレクションが返されます。そのため、コレクションで使用できるeachなどの便利な関数が利用できます。In this example, we'll attach a relation to some created models. When using the create method to create multiple models, an Eloquent collection instance[/docs/{{version}}/eloquent-collections] is returned, allowing you to use any of the convenient functions provided by the collection, such as each:

$users = factory(App\User::class, 3)
           ->create()
           ->each(function ($user) {
                $user->posts()->save(factory(App\Post::class)->make());
            });

関係を複数持つモデルを生成する場合は、createManyメソッドを使用します。You may use the createMany method to create multiple related models:

$user->posts()->createMany(
    factory(App\Post::class, 3)->make()->toArray()
);

リレーションと属性クロージャRelations & Attribute Closures

クロージャ属性をファクトリ定義の中で使い、モデルとのリレーションを追加することもできます。たとえば、Postを作成する時に、新しいUserインスタンスも作成したい場合は、以下のようになります。You may also attach relationships to models using Closure attributes in your factory definitions. For example, if you would like to create a new User instance when creating a Post, you may do the following:

$factory->define(App\Post::class, function ($faker) {
    return [
        'title' => $faker->title,
        'content' => $faker->paragraph,
        'user_id' => function () {
            return factory(App\User::class)->create()->id;
        }
    ];
});

さらに、クロージャは評価済みのファクトリの属性配列を受け取ることもできます。These Closures also receive the evaluated attribute array of the factory that defines them:

$factory->define(App\Post::class, function ($faker) {
    return [
        'title' => $faker->title,
        'content' => $faker->paragraph,
        'user_id' => function () {
            return factory(App\User::class)->create()->id;
        },
        'user_type' => function (array $post) {
            return App\User::find($post['user_id'])->type;
        }
    ];
});

シーダの使用Using Seeds

テストでデータベースへ初期値を設定するために、データベースシーダを使いたい場合は、seedメソッドを使用してください。デフォルトでseedメソッドは、他のシーダーを全部実行するDatabaseSeederを返します。もしくは、seedメソッドへ特定のシーダクラス名を渡してください。If you would like to use database seeders[/docs/{{version}}/seeding] to populate your database during a test, you may use the seed method. By default, the seed method will return the DatabaseSeeder, which should execute all of your other seeders. Alternatively, you pass a specific seeder class name to the seed method:

<?php

namespace Tests\Feature;

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

class ExampleTest extends TestCase
{
    use RefreshDatabase;

    /**
     * Test creating a new order.
     *
     * @return void
     */
    public function testCreatingANewOrder()
    {
        // DatabaseSeederを実行
        $this->seed();

        // シーダを1つ実行
        $this->seed(OrderStatusesTableSeeder::class);

        // ...
    }
}

使用可能なアサーションAvailable Assertions

Laravelは、多くのデータベースアサーションをPHPUnitテスト向けに提供しています。Laravel provides several database assertions for your PHPUnit[https://phpunit.de/] tests:

メソッドMethod 説明Description
$this->assertDatabaseHas($table, array $data);$this->assertDatabaseHas($table, array $data); 指定したデータが、テーブルに存在することをアサートAssert that a table in the database contains the given data.
$this->assertDatabaseMissing($table, array $data);$this->assertDatabaseMissing($table, array $data); 指定したデータが、テーブルに含まれないことをアサートAssert that a table in the database does not contain the given data.
$this->assertSoftDeleted($table, array $data);$this->assertSoftDeleted($table, array $data); 指定したレコードがソフトデリートされていることをアサートAssert that the given record has been soft deleted.

章選択

設定

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

ヘッダー項目移動

キーボード操作