【问题标题】:How can I pass all required fields on testing updated method in a clean way?如何以干净的方式通过测试更新方法的所有必填字段?
【发布时间】:2019-02-16 02:27:49
【问题描述】:

我想测试我的更新功能。我可以在浏览器上更新产品,但我无法通过测试。

这里是我的更新方法:

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

我知道我必须传递所有数据,但我怎样才能以一种干净的方式传递它?能给我举个例子吗?

【问题讨论】:

    标签: php laravel unit-testing testing


    【解决方案1】:

    我认为最简洁的方法是将控制器中的验证逻辑抽象为表单请求。

    在此处查看文档 - https://laravel.com/docs/5.7/validation#creating-form-requests

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-08
      • 2014-11-30
      • 2011-11-05
      • 1970-01-01
      相关资源
      最近更新 更多