LoginSignup
8
1

More than 5 years have passed since last update.

Fakerを利用してテストごとにテストデータを入れる方法

Posted at

fixtureでデータの管理をしていたが、テストデータが増えると辛い面が多かった。
そこで、RubyのFactoryGirlのようにテストごとにデータを作りたかった。

環境

PHP 7.0
cakePHP 3.4

Faker

フェイクデータを作ってくれるライブラリです。
フェイクデータ以外にもデータを作成してDBに突っ込んでくれる機能があるようなのでそれを利用します。

インストール

composerを使ってインストール

composer require fzaninotto/faker

使い方

この辺を参考にしてやってみる。

例えばUsersTableのテストを行う場合。

UsersTableTest.php

public function setUp()
{
    // 他の初期処理省略

    // 初期処理でpopulatorの作成、cakePHP以外のORMの指定も可能
    $this->populator = new \Faker\ORM\CakePHP\Populator(
        \Faker\Factory::create()
    );
}

// 実際のテスト
public function testHogehoge()
{
    $this->populator->addEntity(
        'Users',
        10, // 10件データを作成する
        [
            // データを指定したい場合はここで指定
            'birthday' => '2018-01-19'
        ]
    );
    // 戻り値は作成されたデータのID
    $insertedPKs = $this->populator->execute();

    $this->assertCount(10, $insertedPKs['User']);

}

アソシエーションの紐付けを指定したい場合は普通にやってもうまくいかなかったが、下記のようにするとなんとかできた。

UsersTableTest.php

public function testHogehoge()
{
    $this->populator->addEntity('Groups', 5);
    $this->populator->addEntity(
        'Users',
        1,
        [
            'birthday' => '2018-01-19'
        ],
        [
            // アソシエーションIDの指定はここで指定
            'belongsToGroups' => function($user){
                $user->group_id = 3;
                return $user; 
            }
        ]
    );

    $insertedPKs = $this->populator->execute();

    $user = User->find()->where(['id' => $insertedPKs['User']])->first();
    $this->assertCount(3, $user->group_id);
}

これで、なんとかテストごとにデータを入れれそう。

8
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
1