Laravel 5:型号 - >填写()忽略单元测试$可填写的财产(Laravel 5: Mo

2019-10-23 11:16发布

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

My User.php model defines the fillable properties as:

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

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

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.

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).

Thanks,

Edit

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.

Answer 1:

发现了问题:在v5.0.x基播种机仅称为型号:: unguard()( https://github.com/laravel/laravel/blob/v5.0.22/database/seeds/DatabaseSeeder.php#L15 )而v5.1.x进行了更新,并加入到模型中调用:: reguard()( https://github.com/laravel/laravel/blob/v5.1.0/database/seeds/DatabaseSeeder.php#L19 )(我使用v5.0.22)。



Answer 2:

可输入资料只适用于MassAssignment。 当你创建一个新的实例,就像你在上面做什么,你不触发质量分配事件。

你可以做这样的事情:如果你无论如何创建用户,您不妨这样做:

$user = User::create($request->all);

如果你只是想实例化的用户,无需持续的数据,你可以这样做:

$user = new User($request);


文章来源: Laravel 5: Model->fill() ignores $fillable property in unit tests