我有一个使用Blameable
行为的模型:
class Vehicle extends ActiveRecord
{
// ...
public function behaviors()
{
return [
'blameable' => [
'class' => BlameableBehavior::className(),
'createdByAttribute' => 'UserID',
'updatedByAttribute' => null,
]
];
}
// ...
}
问题是当我尝试保存Vehicle
的实例以便使用特定的UserID进行测试时,Blameable
将覆盖该值为null(因为没有用户设置为当前登录)并保存该模型将失败。
这段剪辑说明了我到目前为止如何解决这个问题:
$owner = $this->createUser(); // creates user with fake data
Yii::$app->user->setIdentity($owner);
$vehicle = $this->createVehicle(); // creates vehicle and relies that the $owner->UserID will be set when vehicle is being saved
但是我不喜欢它,因为事先设置用户身份的原因并不明显。有没有办法在测试中禁用Blameable
行为?
答案 0 :(得分:3)
只需在createVehicle()
方法中分离BlamableBehavior,如下所示:
public function createVehile()
{
$vehicle = new Vehicle();
$vehicle->detachBehavior('blameable');
// ...
}
答案 1 :(得分:0)
对于使用'/' + encodeURI('https://www.../posts/the-post-title-url') + '/comments'
的用户来说,分离行为无法解决问题,因为调用新模型仍然会引发错误。
相反,您可以使用_before方法来设置所有测试的标识。
单元测试
'value' => Yii::$app->user->identity->username
各种模型行为
use app\models\User; // your user class
class SupplierTest extends \Codeception\Test\Unit
{
protected function _before()
{
// Required for model blameable behavior using Yii@.
$owner = new User();
$owner->username = 'tester';
$owner->auth_key = '123456';
$owner->password_hash = '123456';
$owner->email = 'something@some.com';
$owner->save();
Yii::$app->user->setIdentity($owner);
}
public function testCreateRecord() {
$rec = new Supplier();
$rec->supplier = "Supplier ABC";
$rec->smr_number = "123456";
$rec->validate();
Debug::debug($rec->getErrors());
$this->assertTrue($rec->save());
}