使用可归责行为时进行Yii2测试

时间:2016-10-18 15:27:41

标签: php yii2

我有一个使用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行为?

2 个答案:

答案 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());
    }