Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing fixture record in yii2/codeception data files

Is there a way to specify a related row of another fixture in fixture data file in Yii2/Codeception ActiveFixture? Consider this example of user/profile relation:

user.php:

return [
    'user1' => [
        'email' => '[email protected]',
     ]
];

profile.php:

use common\models\User;
return [
    'profile1' => [
        'user_id' => User::findOne(['email' => '[email protected]'])->id;
        'name' => 'My Name',
     ]
];

The documentation states that "You may give an alias to a row so that later in your test, you may refer to the row via the alias." Is there a way to reference rows inside another fixture? For example, use something like $this->user('user1')->id in profile.php? I could not find any mention on how to do that. How do you create this kind of related fixtures?

like image 857
Andrey Avatar asked Dec 18 '14 10:12

Andrey


2 Answers

Aliased data can be accessed only inside scope of dedicated Fixture object through its data property after its load() method has been executed. The only way to make this data accessible from data file of another Fixture object is to register it with some global object, for example Application object.

I usually just query all needed data before constructing dependent dataset:

use common\models\User;
$users = User::find()->indexBy('email')->all();
return [
    'profile1' => [
        'user_id' => $users['[email protected]']->id,
        'name' => 'My Name',
     ]
];
like image 73
HongKilDong Avatar answered Oct 13 '22 01:10

HongKilDong


I use Faker with Yii2. When I started to write test, I found out that I need good fixtures. In yii2 there is yii2-faker/FixtureController , that can generate fixtures. More in documentation

But I get the same problem as author. I need to genereate fixtures for users, profiles(that contain user_id) and roles . I didn't found a solution in documentation, how to do it, but this work for me.

Templates: users.php

return [
'id' => $index +1 ,
'login' => $faker->unique()->safeEmail,
'password' => $user->hashPassword('123qwe'),
'type' => '0',
'is_active' => '1',
'is_verified' => '1',
'created_at' => time(),
'updated_at' => time(),

];

profiles.php

return [
'id' => $index +1 ,
'user_id' => $index +1 ,
'first_name' => $faker->firstName,
'last_name' => $faker->lastName,
'middle_name' => $faker->optional()->firstName,
'phone' => $faker->unique()->phoneNumber,
'contact_email' => $faker->email

];

The main feature here is - $index.

`$index`: the current fixture index. For example if user need to generate 3 fixtures for user table, it will be 0..2.

So I could know what id would be in user and insert it into profile.

After that I run the command:

php yii fixture/generate users profiles --count=100

And have generated 100 users with profiles. I hope it helps some one.

like image 40
Colohanin Nik Avatar answered Oct 13 '22 01:10

Colohanin Nik