在 yii2/codeception 数据文件中引用夹具记录

Posted

技术标签:

【中文标题】在 yii2/codeception 数据文件中引用夹具记录【英文标题】:Referencing fixture record in yii2/codeception data files 【发布时间】:2015-02-17 02:48:27 【问题描述】:

有没有办法在 Yii2/Codeception ActiveFixture 的夹具数据文件中指定另一个夹具的相关行?考虑这个用户/个人资料关系的例子:

user.php:

return [
    'user1' => [
        'email' => 'user1@example.net',
     ]
];

profile.php:

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

文档声明“您可以为一行指定别名,以便稍后在您的测试中,您可以通过别名引用该行。”有没有办法引用另一个夹具内的行?例如,在 profile.php 中使用类似 $this->user('user1')->id 的东西?我找不到任何关于如何做到这一点的提及。你如何创建这种相关的灯具?

【问题讨论】:

【参考方案1】:

我在 Yii2 中使用 Faker。 当我开始编写测试时,我发现我需要好的夹具。 在 yii2 中有 yii2-faker/FixtureController ,可以生成夹具。 More in documentation

但我遇到了与作者相同的问题。我需要为用户、配置文件(包含 user_id)和角色生成固定装置。我没有在文档中找到解决方案,如何去做,但这对我有用。

模板: 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

];

这里的主要特征是-$index。

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

所以我可以知道用户中的 id 并将其插入到配置文件中。

之后我运行命令:

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

并且已经生成了 100 个用户的个人资料。 希望对大家有所帮助。

【讨论】:

【参考方案2】:

在其load() 方法执行后,别名数据只能在专用Fixture 对象范围内通过其data 属性访问。使这些数据可以从另一个 Fixture 对象的数据文件中访问的唯一方法是将其注册到某个全局对象,例如 Application 对象。

我通常只是在构建依赖数据集之前查询所有需要的数据:

use common\models\User;
$users = User::find()->indexBy('email')->all();
return [
    'profile1' => [
        'user_id' => $users['user1@example.net']->id,
        'name' => 'My Name',
     ]
];

【讨论】:

以上是关于在 yii2/codeception 数据文件中引用夹具记录的主要内容,如果未能解决你的问题,请参考以下文章

如何将多个选项传递给 Firefox 中引导轮播的可选选项对象?

自动布局中引脚和对齐之间的区别?

Redis配置文件

ngnix相关

ValueError:在 defaultdict 上使用 sklearn 时样本数不一致

python培训