Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 testing when using blameable behavior

Tags:

php

yii2

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?

like image 895
ddinchev Avatar asked Oct 18 '16 15:10

ddinchev


1 Answers

Just detach the BlamableBehavior in your createVehicle() method as follows:

public function createVehile()
{
    $vehicle = new Vehicle();
    $vehicle->detachBehavior('blameable');
    // ...
}
like image 187
SilverFire Avatar answered Nov 19 '22 11:11

SilverFire