Laravel 5:Model-> fill()在单元测试中忽略$ fillable属性 [英] Laravel 5: Model->fill() ignores $fillable property in unit tests

查看:173
本文介绍了Laravel 5:Model-> fill()在单元测试中忽略$ fillable属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下验证规则的用户控制器:

I have a user controller with the following validation rules:

public function store(Request $request)
{
    ...
    $this->validate($request, [
        'name' => 'required',
        'email' => 'email|required|unique:users',
        'password' => 'confirmed|max:32|min:8|required',
        'roles' => 'exists:roles,id|required',
    ]);

    $user = new User();
    $user->fill($request->all());
   ...
}

我的User.php模型将可填充属性定义为:

My User.php model defines the fillable properties as:

protected $fillable = ['name', 'email'];

要通过confirmed验证,我必须在POST请求中同时发送passwordpassword_confirmation字段.

To pass the confirmed validation, I have to send both password and password_confirmation fields in the POST request.

在开发过程中,一切正常,但是在单元测试中,我遇到了数据库错误.它尝试将数据插入password_confirmation列.就像它忽略了$fillable数组.

During development everything works fine, but in unit tests I'm getting a database error. It tries to insert data into a password_confirmation column. It's like it ignores the $fillable array.

我知道测试之间的laravel丢失事件处理程序"错误/问题( https://github.com/laravel/framework/issues/1181 ).因此,我认为也许除了Model::boot()之外,我缺少调用某些模型函数(我在测试的setUp()函数中调用User::boot()).

I know about the "laravel losts event handlers between tests" bug/issue (https://github.com/laravel/framework/issues/1181). So I think that maybe I'm missing to call some model function aside from Model::boot() (I'm calling User::boot() in the test's setUp() function).

谢谢

在阅读Model.php源代码时,我发现有人正在呼叫Model::unguard()

Reading the Model.php source, I've found that someone is calling Model::unguard() https://github.com/laravel/framework/blob/5.1/src/Illuminate/Database/Eloquent/Model.php#L2180 after the setUp() function and before the test. If I call User::reguard() at the beggining of the test it passes, but (I don't know why), the unguard() and reguard() functions get called multiple times and the test gets really slow.

推荐答案

发现了问题:v5.0.x中的基础种子仅被称为Model :: unguard()(

Found the problem: the base seeder in v5.0.x only called Model::unguard() (https://github.com/laravel/laravel/blob/v5.0.22/database/seeds/DatabaseSeeder.php#L15) while v5.1.x was updated and added a call to Model::reguard() (https://github.com/laravel/laravel/blob/v5.1.0/database/seeds/DatabaseSeeder.php#L19) (I was using v5.0.22).

这篇关于Laravel 5:Model-> fill()在单元测试中忽略$ fillable属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆