电子邮件验证.从网站访问时工作,但未通过单元测试


Email validation. Working when accessed from the website, but fails the unit test

我今天遇到了一个相当奇怪的问题。

我设置了一个具有以下规则的模型:

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

当通过控制器访问时,这将相应地工作。但是我的单位验证电子邮件时测试失败:

    $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);

我在表单中使用相同的电子邮件,其中数据按应有的方式进入数据库。但是当在这里使用时,在第二次电子邮件验证时失败。

我尝试了其他电子邮件格式,但这也不能解决问题。有什么想法吗?

如果您转储错误getErrors(),您会发现失败的不是电子邮件验证。

它不起作用的原因是您没有指定要验证为数组的属性:

如果您查看Validator代码(validate() -call 最终结束的地方):

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

基本上:如果它不是一个数组,它就会被抛出,所以它会验证所有属性。

将其更改为$this->assertFalse($model->validate(['email']), 'Email is invalid.');,它应该可以工作

编辑:顺便说一句,这是一个很容易犯的错误,因为框架确实在很多其他地方将单个字符串转换为数组。所以这种行为并不是真正一致的。