Email authentication. Works when accessed from website but unit test fails

I ran into a rather strange problem today.

I created a model with these rules:

public function rules()
{
    return [
        [['name', 'email', 'website'], 'required'],
        [['name'], 'string', 'max' => 512],
        [['name'], 'unique'],
        [['email'], 'email'],
        [['website'], 'url'],
    ];
}

      

This works when accessed through a controller. However, my unit failed to validate email validation:

    $model->email = 'somethinghan.nl';
    $this->assertFalse($model->validate('email'),
        'Email is invalid.');
    $model->email = 'student@han.nl';
    $this->assertTrue($model->validate('email'),
        'Validating email with a valid email: ' . $model->email);

      

I used the same email in the form where data is fed into the database as needed. But when used here, it crashes when re-checking email.

I've tried other email formats but that doesn't fix the problem either. Any ideas?

+3


source to share


1 answer


If you reset the errors with getErrors()

, you will see that it is not the email authentication that is failing.

The reason it doesn't work is because you don't specify the attributes to be validated as an array:

If you look at the Validator

-code
(where validate()

-call ends ):

public function validateAttributes($model, $attributes = null)
{
    if (is_array($attributes)) {
        $attributes = array_intersect($this->attributes, $attributes);
    } else {
        $attributes = $this->attributes;
    }
    ...
}

      



So basically: if it's not an array it gets thrown away, so it checks all the attributes.

Change it to $this->assertFalse($model->validate(['email']), 'Email is invalid.');

and it should work

Edit: BTW, this is a very simple mistake as the framework does one string to array conversion in many other places. Thus, this behavior is inconsistent.

+4


source







All Articles