Codeception Yii2 Module & Sluggable Behavior


(Chris) #1

I have come across an incompatibility between the Yii2 module in Codeception and SluggableBehavior.

SluggableBehavior responds to the BeforeValidate event by default (line 125).




    public function init()

    {

        parent::init();


        if (empty($this->attributes)) {

            $this->attributes = [BaseActiveRecord::EVENT_BEFORE_VALIDATE => $this->slugAttribute];

        }


        if ($this->attribute === null && $this->value === null) {

            throw new InvalidConfigException('Either "attribute" or "value" property must be specified.');

        }

    }



However, the haveRecord() method of the Codeception Yi2 module saves without validation (line 129).




    public function haveRecord($model, $attributes = [])

    {

        /** @var $record \yii\db\ActiveRecord  * */

        $record = $this->getModelRecord($model);

        $record->setAttributes($attributes, false);

        $res = $record->save(false);

        if (!$res) {

            $this->fail("Record $model was not saved");

        }


        return $record->primaryKey;

    }



The work-around is to configure SluggableBehavior to use the BeforeSave event in the behaviors() method of the model, but it is a work-around.

A better solution would be to:

  • Change the default in SluggableBehavior to use the BeforeSave event. As the docs say "Because attribute values will be set automatically by this behavior, they are usually not user input and should therefore not be validated"; if they are not be validated is there value in setting them with the BeforeValidate event? If not BeforeSave would work just fine.

  • Enable validation in the Codeception Yii2 module. This may also be worth doing as it would catch any issues with setting up of model attributes while testing.

  • Both of the above - for the reasons above.

Happy to do a pull request on GitHub for the preferred solution(s)