php – 使用可责备行为时的Yii2测试
发布时间:2020-12-13 17:01:41 所属栏目:PHP教程 来源:网络整理
导读:我有一个使用Blameable行为的模型: class Vehicle extends ActiveRecord { // ... public function behaviors() { return [ 'blameable' = [ 'class' = BlameableBehavior::className(),'createdByAttribute' = 'UserID','updatedByAttribute' = null,] ];
我有一个使用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行为? 解决方法
只需在createVehicle()方法中分离BlamableBehavior,如下所示:
public function createVehile() { $vehicle = new Vehicle(); $vehicle->detachBehavior('blameable'); // ... } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |