我想测试我的更新功能。我可以在浏览器上更新产品,但无法通过测试。
这是我的更新方法:
public function update(Request $request, Product $product)
{
if ($request->hasFile('image')) {
Storage::delete($product->image_path);
$product->update(['image_path' => request()->file('image')->store(auth()->id().'images', 'public')]);
}
$product->update(request()->validate([
'name' => 'required|string',
'description' => 'required|max:255',
'price' => 'required|numeric',
'compare_price' => 'required|numeric',
'charge_tax' => 'boolean',
'sku' =>[
'required',
'numeric',
Rule::unique('products')->ignore($product->id),
],
'inventory' => 'required|numeric',
'track_inventory' => 'required|boolean',
'width' => 'required|numeric',
'height' => 'required|numeric',
'depth' => 'required|numeric',
'weight' => 'required|numeric',
'weight_type' => 'required',
'extra_shipping_fee' => 'required|numeric',
]));
return redirect('/products');
}
这是我的路线:
Route::patch('/products/{product}', 'ProductsController@update');
这是我的考试:
/** @test * */
public function a_product_can_be_updated()
{
$this->signIn();
$product = create('App\Product', ['user_id' => auth()->id()]);
$this->patch($product->path(), // how to pass all data in a short way?
[
'name' => 'changed name',
'sku' => 32123,
]]);
tap($product->fresh(), function ($product) {
$this->assertEquals(32123, $product->sku);
$this->assertEquals('changed name', $product->name);
});
}
我知道我必须传递所有数据,但是如何以一种干净的方式进行传递呢?你能给我举个例子吗?
答案 0 :(得分:0)
我认为最干净的方法是将验证逻辑从控制器抽象为表单请求。
在此处查看文档-https://laravel.com/docs/5.7/validation#creating-form-requests