I have a model using Blameable
behavior:
class Vehicle extends ActiveRecord
{
// ...
public function behaviors()
{
return [
'blameable' => [
'class' => BlameableBehavior::className(),
'createdByAttribute' => 'UserID',
'updatedByAttribute' => null,
]
];
}
// ...
}
The problem is when I try to save an instance of Vehicle
for testing with specific UserID, Blameable
will override that with null (as no user is set to be the current logged in) and save of the model would fail.
This snipped illustrates how I've been solving this so far:
$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
However I don't like it because it's not obvious why the user identity is being set before hand. Is there a way to disable the Blameable
behavior in testing?
Just detach the BlamableBehavior in your createVehicle()
method as follows:
public function createVehile()
{
$vehicle = new Vehicle();
$vehicle->detachBehavior('blameable');
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With