路由模型绑定在功能测试laravel 8上无法正常工作

at0kjp5o  于 2022-12-24  发布在  其他
关注(0)|答案(2)|浏览(88)

在对补丁端点进行特性测试时,我在控制器更新方法中获得了新的雄辩示例,而不是所需的雄辩模型。在PurchaseTest.php中生成的雄辩模型没有通过路由模型绑定传递到PurchaseController.php。但当我通过浏览器使用路由时,路由工作正常。

网页. php
Route::name('admin.')->middleware(['admin'])->prefix('admin')->group(function () {
    Route::name('purchases.')->prefix('/purchases')->group(function () {
        Route::patch('/{purchase}/update', 'PurchaseController@update')->name('update');
    });
});
购买测试. php
class PurchaseTest extends TestCase
{
    use RefreshDatabase;
    use WithoutMiddleware;

    public function test_purchase_can_be_updated()
    {
        $purchase = Purchase::create([
            "item" => "tariqs item",
            "support" => "2022-09-09",
            "status" => PurchaseStatus::ACTIVE,
            "purchase_code" => "1234",
            "username" => "tariq",
            "user_id" => "1",
        ]);
        
        // $purchase model is not passing to controller through this patch request.
        $response = $this->patch(route('admin.purchases.update', compact('purchase')), [
            "item" => "tariqs item edit",
            "support" => "2022-09-09",
            "status" => PurchaseStatus::ACTIVE,
            "purchase_code" => "1234",
            "username" => "tariq",
        ]);

        $response->assertStatus(200);
    }
}
采购控制器. php
public function update(Request $request, Purchase $purchase)
    {
        dd($purchase, $request->all());  // here $purchase is a new instance of $purchase, not the desired $purchase model.

        $input = $request->validate([
            "item" => "required|string",
            "support" => "required|date_format:Y-m-d",
            "status" => "required|string",
            "purchase_code" => "required|string",
            "username" => "required|string",
        ]);

        if ($purchase->update($input)) {
            $purchases = Purchase::where('user_id', $purchase->user_id)->get();
            return response()->json(['success' => 'true', 'msg' => __("Purchase code successfully updated."), 'embed' => view('admin.misc.purchase-list', compact('purchases'))->render()]);
        }

        throw ValidationException::withMessages(['error' => __('Something went wrong.')]);
    }
pxyaymoc

pxyaymoc1#

您可能需要在不使用compact()的情况下执行route('admin.purchases.update', $purchase)route('admin.purchases.update', $purchase->id)之类的路由呼叫

rjee0c15

rjee0c152#

我终于解决了这个问题!
验证您是否在测试中使用了Trait WithoutMiddleware如果是,请将其删除!
在我的情况下,这是问题!I found here.
在Laravel中,模型路由绑定是由middleware完成的,所以当我使用这个Trait时,我删除了所有middlewares

相关问题