Readouble

Laravel 8.x データベーステスト

イントロダクションIntroduction

データベース駆動型アプリケーションのテストを容易にするため、Laravelはさまざまな便利なツールとアサートを提供しています。それに加えて、Laravelモデルのファクトリ(テスト用インスタンスの生成)とシーダ(初期データ設定)により、アプリケーションのEloquentモデルとリレーションを使用し、テストデータベースレコードを簡単に作成できます。これらの強力な機能のすべてについて、以降のドキュメントで説明します。Laravel provides a variety of helpful tools and assertions to make it easier to test your database driven applications. In addition, Laravel model factories and seeders make it painless to create test database records using your application's Eloquent models and relationships. We'll discuss all of these powerful features in the following documentation.

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

先へ進む前に、以前のテストデータが後続のテストに干渉しないように、各テストの後にデータベースをリセットする方法について説明しましょう。Laravelに含まれているIlluminate\Foundation\Testing\RefreshDatabaseトレイトがこれを処理します。テストクラスでトレイトを使用するだけです。Before proceeding much further, let's discuss how to reset your database after each of your tests so that data from a previous test does not interfere with subsequent tests. Laravel's included Illuminate\Foundation\Testing\RefreshDatabase trait will take care of this for you. Simply use the trait on your test class:

<?php

namespace Tests\Feature;

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

class ExampleTest extends TestCase
{
    use RefreshDatabase;

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

        // ...
    }
}

モデルファクトリの定義Defining Model Factories

コンセプトの概要Concept Overview

まず、Eloquentモデルファクトリについて説明しましょう。テストするときは、テストを実行する前に、データベースにいくらかのレコードを挿入する必要があります。このテストデータを作成するときに各カラムの値を自分でいちいち指定する代わりに、Laravelではモデルファクトリを使用し、各Eloquentモデルのデフォルト属性を定義できます。First, let's talk about Eloquent model factories. 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 set of default attributes for each of your Eloquent models[/docs/{{version}}/eloquent] using model factories.

ファクトリの作成方法の例を確認するには、アプリケーションのdatabase/factorys/UserFactory.phpファイルを見てください。このファクトリはすべての新しいLaravelアプリケーションに含まれており、以下のファクトリ定義が含まれています。To see an example of how to write a factory, take a look at the database/factories/UserFactory.php file in your application. This factory is included with all new Laravel applications and contains the following factory definition:

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class UserFactory extends Factory
{
    /**
     * モデルのデフォルト状態の定義
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name(),
            'email' => $this->faker->unique()->safeEmail(),
            'email_verified_at' => now(),
            'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
            'remember_token' => Str::random(10),
        ];
    }
}

ご覧のとおり、一番基本的な形式では、ファクトリはLaravelの基本ファクトリクラスを拡張し、definitionメソッドを定義するクラスです。definitionメソッドは、ファクトリを使用してモデルを作成するときに適用する必要がある属性値のデフォルトセットを返します。As you can see, in their most basic form, factories are classes that extend Laravel's base factory class and define definition method. The definition method returns the default set of attribute values that should be applied when creating a model using the factory.

ファクトリはfakerプロパティを介して、Faker PHPライブラリにアクセスできます。これにより、テスト用のさまざまな種類のランダムデータを簡単に生成できます。Via the faker property, factories have access to the Faker[https://github.com/FakerPHP/Faker] PHP library, which allows you to conveniently generate various kinds of random data for testing.

lightbulb">Tip!! config/app.php設定ファイルにfaker_localeオプションを追加することで、アプリケーションのFakerロケールを設定できます。{tip} You can set your application's Faker locale by adding a faker_locale option to your config/app.php configuration file.

ファクトリの生成Generating Factories

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

php artisan make:factory PostFactory

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

Model & Factory Discovery ConventionsモデルとファクトリのModel & Factory Discovery Conventions

ファクトリを定義したら、モデルのファクトリインスタンスをインスタンス化するために、Illuminate\Database\Eloquent\Factories\HasFactoryトレイトが、モデルへ提供しているstaticなfactoryメソッドが使用できます。Once you have defined your factories, you may use the static factory method provided to your models by the Illuminate\Database\Eloquent\Factories\HasFactory trait in order to instantiate a factory instance for that model.

HasFactoryトレイトのfactoryメソッドは規約に基づいて、その トレイトが割り当てられているモデルに適したファクトリを決定します。具体的には、Database\Factories名前空間の中でモデル名と一致するクラス名を持ち、サフィックスがFactoryであるファクトリを探します。この規約を特定のアプリケーションやファクトリで適用しない場合は、モデルのnewFactoryメソッドを上書きし、モデルと対応するファクトリのインスタンスを直接返してください。The HasFactory trait's factory method will use conventions to determine the proper factory for the model the trait is assigned to. Specifically, the method will look for a factory in the Database\Factories namespace that has a class name matching the model name and is suffixed with Factory. If these conventions do not apply to your particular application or factory, you may overwrite the newFactory method on your model to return an instance of the model's corresponding factory directly:

use Database\Factories\Administration\FlightFactory;

/**
 * モデルの新ファクトリ・インスタンスの生成
 *
 * @return \Illuminate\Database\Eloquent\Factories\Factory
 */
protected static function newFactory()
{
    return FlightFactory::new();
}

次に、対応するファクトリで、modelプロパティを定義します。Next, define a model property on the corresponding factory:

use App\Administration\Flight;
use Illuminate\Database\Eloquent\Factories\Factory;

class FlightFactory extends Factory
{
    /**
     * モデルと対応するファクトリの名前
     *
     * @var string
     */
    protected $model = Flight::class;
}

ファクトリの状態Factory States

状態操作メソッドを使用すると、モデルファクトリへ任意の組み合わせで適用できる個別の変更を定義できます。たとえば、Database\Factories\UserFactoryファクトリに、デフォルトの属性値の1つを変更するsuspended状態メソッドが含まれているとしましょう。State manipulation methods allow you to define discrete modifications that can be applied to your model factories in any combination. For example, your Database\Factories\UserFactory factory might contain a suspended state method that modifies one of its default attribute values.

状態変換メソッドは通常、Laravelの基本ファクトリクラスが提供するstateメソッドを呼び出します。stateメソッドは、このファクトリ用に定義する素の属性の配列を受け取るクロージャを受け入れ、変更する属性の配列を返す必要があります。State transformation methods typically call the state method provided by Laravel's base factory class. The state method accepts a closure which will receive the array of raw attributes defined for the factory and should return an array of attributes to modify:

/**
 * ユーザーが一時停止されていることを示す
 *
 * @return \Illuminate\Database\Eloquent\Factories\Factory
 */
public function suspended()
{
    return $this->state(function (array $attributes) {
        return [
            'account_status' => 'suspended',
        ];
    });
}

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

ファクトリコールバックは、afterMakingメソッドとafterCreatingメソッドを使用して登録し、モデルの作成または作成後に追加のタスクを実行できるようにします。ファクトリクラスでconfigureメソッドを定義して、これらのコールバックを登録する必要があります。ファクトリがインスタンス化されるときにLaravelが自動的にこのメソッドを呼び出します。Factory callbacks are registered using the afterMaking and afterCreating methods and allow you to perform additional tasks after making or creating a model. You should register these callbacks by defining a configure method on your factory class. This method will be automatically called by Laravel when the factory is instantiated:

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class UserFactory extends Factory
{
    /**
     * モデルファクトリの設定
     *
     * @return $this
     */
    public function configure()
    {
        return $this->afterMaking(function (User $user) {
            //
        })->afterCreating(function (User $user) {
            //
        });
    }

    // ...
}

ファクトリを使用するモデル生成Creating Models Using Factories

モデルのインスタンス化Instantiating Models

ファクトリを定義したら、そのモデルのファクトリインスタンスをインスタンス化するために、Illuminate\Database\Eloquent\Factories\HasFactoryトレイトにより、モデルが提供する静的なfactoryメソッドを使用できます。モデル作成のいくつかの例を見てみましょう。まず、makeメソッドを使用して、データベースへ永続化せずにモデルを作成します。Once you have defined your factories, you may use the static factory method provided to your models by the Illuminate\Database\Eloquent\Factories\HasFactory trait in order to instantiate a factory instance for that model. Let's take a look at a few examples of creating models. First, we'll use the make method to create models without persisting them to the database:

use App\Models\User;

public function test_models_can_be_instantiated()
{
    $user = User::factory()->make();

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

countメソッドを使用して多くのモデルのコレクションを作成できます。You may create a collection of many models using the count method:

$users = User::factory()->count(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 may simply call the state transformation methods directly:

$users = User::factory()->count(5)->suspended()->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 attributes will be replaced while the rest of the attributes remain set to their default values as specified by the factory:

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

もしくは、stateメソッドをファクトリインスタンスで直接呼び出して、インライン状態変更を実行することもできます。Alternatively, the state method may be called directly on the factory instance to perform an inline state transformation:

$user = User::factory()->state([
    'name' => 'Abigail Otwell',
])->make();

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 instantiates model instances and persists them to the database using Eloquent's save method:

use App\Models\User;

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

    // App\Models\Userインスタンスを3つ作成
    $users = User::factory()->count(3)->create();

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

属性の配列をcreateメソッドに渡すことで、ファクトリのデフォルトのモデル属性をオーバーライドできます。You may override the factory's default model attributes by passing an array of attributes to the create method:

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

連続データSequences

モデルを生成するごとに、特定のモデル属性の値を変更したい場合があります。これは、状態変換を連続データとして定義することで実現できます。たとえば、作成されたユーザーごとに、adminカラムの値をYNの間で交互に変更したいとしましょう。Sometimes you may wish to alternate the value of a given model attribute for each created model. You may accomplish this by defining a state transformation as a sequence. For example, you may wish to alternate the value of an admin column between Y and N for each created user:

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Sequence;

$users = User::factory()
                ->count(10)
                ->state(new Sequence(
                    ['admin' => 'Y'],
                    ['admin' => 'N'],
                ))
                ->create();

この例では、admin値がYのユーザーが5人作成され、admin値がNのユーザーが5人作成されます。In this example, five users will be created with an admin value of Y and five users will be created with an admin value of N.

必要に応じて、シーケンス値としてクロージャを含めることができます。新しい値をそのシーケンスが必要とするたびにクロージャを呼び出します。If necessary, you may include a closure as a sequence value. The closure will be invoked each time the sequence needs a new value:

$users = User::factory()
                ->count(10)
                ->state(new Sequence(
                    fn ($sequence) => ['role' => UserRoles::all()->random()],
                ))
                ->create();

シーケンスクロージャ内では,クロージャへ注入されるシーケンスインスタンスの$indexまたは$countプロパティにアクセスできます。$indexプロパティには、これまでに行われたシーケンスの反復回数が格納され、$countプロパティには、シーケンスが起動された合計回数が格納されます。Within a sequence closure, you may access the $index or $count properties on the sequence instance that is injected into the closure. The $index property contains the number of iterations through the sequence that have occurred thus far, while the $count property contains the total number of times the sequence will be invoked:

$users = User::factory()
                ->count(10)
                ->sequence(fn ($sequence) => ['name' => 'Name '.$sequence->index])
                ->create();

リレーションのファクトリFactory Relationships

Has ManyリレーションHas Many Relationships

次に、Laravelの流暢(fluent)なファクトリメソッドを使用して、Eloquentモデルのリレーションを構築する方法を見ていきましょう。まず、アプリケーションにApp\Models\UserモデルとApp\Models\Postモデルがあると想定します。また、UserモデルがPostとのhasManyリレーションを定義していると想定しましょう。 Laravelのファクトリが提供するhasメソッドを使用して、3つの投稿を持つユーザーを作成できます。hasメソッドはファクトリインスタンスを引数に取ります。Next, let's explore building Eloquent model relationships using Laravel's fluent factory methods. First, let's assume our application has an App\Models\User model and an App\Models\Post model. Also, let's assume that the User model defines a hasMany relationship with Post. We can create a user that has three posts using the has method provided by the Laravel's factories. The has method accepts a factory instance:

use App\Models\Post;
use App\Models\User;

$user = User::factory()
            ->has(Post::factory()->count(3))
            ->create();

規約により、Postモデルをhasメソッドに渡す場合、LaravelはUserモデルにリレーションを定義するpostsメソッドが存在していると想定します。必要に応じ、操作するリレーション名を明示的に指定できます。By convention, when passing a Post model to the has method, Laravel will assume that the User model must have a posts method that defines the relationship. If necessary, you may explicitly specify the name of the relationship that you would like to manipulate:

$user = User::factory()
            ->has(Post::factory()->count(3), 'posts')
            ->create();

もちろん、関連モデルで状態を操作することもできます。さらに、状態変更で親モデルへのアクセスが必要な場合は、クロージャベースの状態変換が渡せます。Of course, you may perform state manipulations on the related models. In addition, you may pass a closure based state transformation if your state change requires access to the parent model:

$user = User::factory()
            ->has(
                Post::factory()
                        ->count(3)
                        ->state(function (array $attributes, User $user) {
                            return ['user_type' => $user->type];
                        })
            )
            ->create();

マジックメソッドの使用Using Magic Methods

使いやすいように、Laravelのマジックファクトリリレーションメソッドを使用してリレーションを構築できます。たとえば、以下の例では、規約を使用して、Userモデルのpostsリレーションメソッドを介して作成する必要がある関連モデルを決定します。For convenience, you may use Laravel's magic factory relationship methods to build relationships. For example, the following example will use convention to determine that the related models should be created via a posts relationship method on the User model:

$user = User::factory()
            ->hasPosts(3)
            ->create();

マジックメソッドを使用してファクトリリレーションを作成する場合、属性の配列を渡して、関連モデルをオーバーライドできます。When using magic methods to create factory relationships, you may pass an array of attributes to override on the related models:

$user = User::factory()
            ->hasPosts(3, [
                'published' => false,
            ])
            ->create();

状態の変更で親モデルへのアクセスが必要な場合は、クロージャベースの状態変換を提供できます。You may provide a closure based state transformation if your state change requires access to the parent model:

$user = User::factory()
            ->hasPosts(3, function (array $attributes, User $user) {
                return ['user_type' => $user->type];
            })
            ->create();

Belongs ToリレーションBelongs To Relationships

ファクトリを使用して"has many"リレーションを構築する方法を検討したので、逆の関係を調べてみましょう。forメソッドを使用して、ファクトリが作成したモデルの属する親モデルを定義できます。たとえば、1人のユーザーに属する3つのApp\Models\Postモデルインスタンスを作成できます。Now that we have explored how to build "has many" relationships using factories, let's explore the inverse of the relationship. The for method may be used to define the parent model that factory created models belong to. For example, we can create three App\Models\Post model instances that belong to a single user:

use App\Models\Post;
use App\Models\User;

$posts = Post::factory()
            ->count(3)
            ->for(User::factory()->state([
                'name' => 'Jessica Archer',
            ]))
            ->create();

作成するモデルに関連付ける必要のある親モデルインスタンスがすでにある場合は、モデルインスタンスをforメソッドに渡すことができます。If you already have a parent model instance that should be associated with the models you are creating, you may pass the model instance to the for method:

$user = User::factory()->create();

$posts = Post::factory()
            ->count(3)
            ->for($user)
            ->create();

マジックメソッドの使用Using Magic Methods

便利なように、Laravelのマジックファクトリリレーションシップメソッドを使用して、"belongs to"リレーションシップを定義できます。たとえば、以下の例では、3つの投稿がPostモデルのuserリレーションに属する必要があることを規約を使用して決定しています。For convenience, you may use Laravel's magic factory relationship methods to define "belongs to" relationships. For example, the following example will use convention to determine that the three posts should belong to the user relationship on the Post model:

$posts = Post::factory()
            ->count(3)
            ->forUser([
                'name' => 'Jessica Archer',
            ])
            ->create();

Many To ManyリレーションMany To Many Relationships

has manyリレーションと同様に、"many to many"リレーションは、hasメソッドを使用して作成できます。Like has many relationships[#has-many-relationships], "many to many" relationships may be created using the has method:

use App\Models\Role;
use App\Models\User;

$user = User::factory()
            ->has(Role::factory()->count(3))
            ->create();

ピボットテーブルの属性Pivot Table Attributes

モデルをリンクするピボット/中間テーブルへ設定する属性を定義する必要がある場合は、hasAttachedメソッドを使用します。このメソッドは、ピボットテーブルの属性名と値の配列を2番目の引数に取ります。If you need to define attributes that should be set on the pivot / intermediate table linking the models, you may use the hasAttached method. This method accepts an array of pivot table attribute names and values as its second argument:

use App\Models\Role;
use App\Models\User;

$user = User::factory()
            ->hasAttached(
                Role::factory()->count(3),
                ['active' => true]
            )
            ->create();

状態変更で関連モデルへのアクセスが必要な場合は、クロージャベースの状態変換を指定できます。You may provide a closure based state transformation if your state change requires access to the related model:

$user = User::factory()
            ->hasAttached(
                Role::factory()
                    ->count(3)
                    ->state(function (array $attributes, User $user) {
                        return ['name' => $user->name.' Role'];
                    }),
                ['active' => true]
            )
            ->create();

作成しているモデルへアタッチしたいモデルインスタンスがすでにある場合は、モデルインスタンスをhasAttachedメソッドへ渡せます。この例では、同じ3つの役割が3人のユーザーすべてに関連付けられます。If you already have model instances that you would like to be attached to the models you are creating, you may pass the model instances to the hasAttached method. In this example, the same three roles will be attached to all three users:

$roles = Role::factory()->count(3)->create();

$user = User::factory()
            ->count(3)
            ->hasAttached($roles, ['active' => true])
            ->create();

マジックメソッドの使用Using Magic Methods

利便性のため、Laravelのマジックファクトリリレーションメソッドを使用して、多対多のリレーションを定義できます。たとえば、次の例では、関連するモデルをUserモデルのrolesリレーションメソッドを介して作成する必要があることを規約を使用して決定します。For convenience, you may use Laravel's magic factory relationship methods to define many to many relationships. For example, the following example will use convention to determine that the related models should be created via a roles relationship method on the User model:

$user = User::factory()
            ->hasRoles(1, [
                'name' => 'Editor'
            ])
            ->create();

ポリモーフィックリレーションPolymorphic Relationships

ポリモーフィックな関係もファクトリを使用して作成できます。ポリモーフィックな"morph many"リレーションは、通常の"has many"リレーションと同じ方法で作成します。たとえば、 App\Models\PostモデルがApp\Models\CommentモデルとmorphMany関係を持っている場合は以下のようになります。Polymorphic relationships[/docs/{{version}}/eloquent-relationships#polymorphic-relationships] may also be created using factories. Polymorphic "morph many" relationships are created in the same way as typical "has many" relationships. For example, if a App\Models\Post model has a morphMany relationship with a App\Models\Comment model:

use App\Models\Post;

$post = Post::factory()->hasComments(3)->create();

Morph ToリレーションMorph To Relationships

マジックメソッドを使用してmorphTo関係を作成することはできません。代わりに、forメソッドを直接使用し、関係の名前を明示的に指定する必要があります。たとえば、CommentモデルにmorphTo関係を定義する commentableメソッドがあると想像してください。この状況でforメソッドを直接使用し、1つの投稿に属する3つのコメントを作成できます。Magic methods may not be used to create morphTo relationships. Instead, the for method must be used directly and the name of the relationship must be explicitly provided. For example, imagine that the Comment model has a commentable method that defines a morphTo relationship. In this situation, we may create three comments that belong to a single post by using the for method directly:

$comments = Comment::factory()->count(3)->for(
    Post::factory(), 'commentable'
)->create();

ポリモーフィック多対多リレーションPolymorphic Many To Many Relationships

ポリモーフィック「多対多」(morphToMany morphedByMany)リレーションは、ポリモーフィックではない「多対多」リレーションと同じように作成できます。Polymorphic "many to many" (morphToMany / morphedByMany) relationships may be created just like non-polymorphic "many to many" relationships:

use App\Models\Tag;
use App\Models\Video;

$videos = Video::factory()
            ->hasAttached(
                Tag::factory()->count(3),
                ['public' => true]
            )
            ->create();

もちろん、hasマジックメソッドを使用して、ポリモーフィックな「多対多」リレーションを作成することもできます。Of course, the magic has method may also be used to create polymorphic "many to many" relationships:

$videos = Video::factory()
            ->hasTags(3, ['public' => true])
            ->create();

ファクトリ内でのリレーション定義Defining Relationships Within Factories

モデルファクトリ内でリレーションを定義するには、リレーションの外部キーへ新しいファクトリインスタンスを割り当てます。これは通常、belongsTomorphToリレーションなどの「逆」関係で行います。たとえば、投稿を作成時に新しいユーザーを作成する場合は、次のようにします。To define a relationship within your model factory, you will typically assign a new factory instance to the foreign key of the relationship. This is normally done for the "inverse" relationships such as belongsTo and morphTo relationships. For example, if you would like to create a new user when creating a post, you may do the following:

use App\Models\User;

/**
 * モデルのデフォルト状態の定義
 *
 * @return array
 */
public function definition()
{
    return [
        'user_id' => User::factory(),
        'title' => $this->faker->title(),
        'content' => $this->faker->paragraph(),
    ];
}

リレーションのカラムがそれを定義するファクトリに依存している場合は、属性にクロージャを割り当てることができます。クロージャは、ファクトリの評価済み属性配列を受け取ります。If the relationship's columns depend on the factory that defines it you may assign a closure to an attribute. The closure will receive the factory's evaluated attribute array:

/**
 * モデルのデフォルト状態の定義
 *
 * @return array
 */
public function definition()
{
    return [
        'user_id' => User::factory(),
        'user_type' => function (array $attributes) {
            return User::find($attributes['user_id'])->type;
        },
        'title' => $this->faker->title(),
        'content' => $this->faker->paragraph(),
    ];
}

シーダの実行Running Seeders

機能テスト中にデータベースシーダ(初期値設定)を使用してデータベースへデータを入力する場合は、seedメソッドを呼び出してください。seedメソッドはデフォルトで、DatabaseSeederを実行します。これにより、他のすべてのシーダが実行されます。または、特定のシーダクラス名をseedメソッドに渡します。If you would like to use database seeders[/docs/{{version}}/seeding] to populate your database during a feature test, you may invoke the seed method. By default, the seed method will execute 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 Database\Seeders\OrderStatusSeeder;
use Database\Seeders\TransactionStatusSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\TestCase;

class ExampleTest extends TestCase
{
    use RefreshDatabase;

    /**
     * 新しい注文の作成をテスト
     *
     * @return void
     */
    public function test_orders_can_be_created()
    {
        // DatabaseSeederを実行
        $this->seed();

        // 特定のシーダを実行
        $this->seed(OrderStatusSeeder::class);

        // ...

        // 配列中に指定してあるシーダを実行
        $this->seed([
            OrderStatusSeeder::class,
            TransactionStatusSeeder::class,
            // ...
        ]);
    }
}

あるいは、RefreshDatabaseトレイトを使用する各テストの前に、自動的にデータベースをシードするようにLaravelに指示することもできます。これを実現するには、テストの基本クラスに$seedプロパティを定義します。Alternatively, you may instruct Laravel to automatically seed the database before each test that uses the RefreshDatabase trait. You may accomplish this by defining a $seed property on your base test class:

<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    /**
     * デフォルトのシーダーが各テストの前に実行するかを示す
     *
     * @var bool
     */
    protected $seed = true;
}

$seedプロパティが true の場合、RefreshDatabaseトレイトを使用する各テストの前にDatabase\Seeders\DatabaseSeederクラスを実行します。ただし,テストクラスに$seederプロパティを定義し,実行したい特定のシーダーを指定できます。When the $seed property is true, the test will run the Database\Seeders\DatabaseSeeder class before each test that uses the RefreshDatabase trait. However, you may specify a specific seeder that should be executed by defining a $seeder property on your test class:

use Database\Seeders\OrderStatusSeeder;

/**
 * 各テストの前に特定のシーダーを実行
 *
 * @var string
 */
protected $seeder = OrderStatusSeeder::class;

利用可能なアサートAvailable Assertions

Laravelは、PHPUnit機能テスト用にいくつかのデータベースアサートを提供しています。以下にこのようなアサートについて説明します。Laravel provides several database assertions for your PHPUnit[https://phpunit.de/] feature tests. We'll discuss each of these assertions below.

assertDatabaseCountassertDatabaseCount

データベース内のテーブルに指定した数のレコードが含まれていることをアサートします。Assert that a table in the database contains the given number of records:

$this->assertDatabaseCount('users', 5);

assertDatabaseHasassertDatabaseHas

データベース内のテーブルに、指定したキー/値クエリの制約に一致するレコードが含まれていることをアサートします。Assert that a table in the database contains records matching the given key / value query constraints:

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

assertDatabaseMissingassertDatabaseMissing

データベース内のテーブルに、指定したキー/値クエリの制約に一致するレコードが含まれていないことをアサートします。Assert that a table in the database does not contain records matching the given key / value query constraints:

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

assertDeletedassertDeleted

assertDeletedは、指定したEloquentモデルがデータベースから削除されたことをアサートします。The assertDeleted asserts that a given Eloquent model has been deleted from the database:

use App\Models\User;

$user = User::find(1);

$user->delete();

$this->assertDeleted($user);

assertSoftDeletedメソッドは、指定したEloquentモデルが「ソフト削除」されたことをアサートします。The assertSoftDeleted method may be used to assert a given Eloquent model has been "soft deleted":

$this->assertSoftDeleted($user);

assertModelExistsassertModelExists

指定モデルがデータベースに存在することをアサートします。Assert that a given model exists in the database:

use App\Models\User;

$user = User::factory()->create();

$this->assertModelExists($user);

assertModelMissingassertModelMissing

指定モデルがデータベースに存在しないことをアサートします。Assert that a given model does not exist in the database:

use App\Models\User;

$user = User::factory()->create();

$user->delete();

$this->assertModelMissing($user);

章選択

設定

明暗テーマ
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!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

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

コードフォント

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

保存内容リセット

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

ヘッダー項目移動

キーボード操作