Why am I receiving this error? Seems like I am doing everything correctly
Test:
public function test_user_can_add_product_to_cart()
{
$user = User::factory()->create();
$this->actingAs($user);
$response = $this->post('addProductToCart', ['quantity' => 4], [
Product::first(),
]);
$response->assertRedirect('/products');
}
Route:
Route::middleware([auth::class])->group(function () {
Route::post('/cart/add/{product}', [CartController::class, 'addProductToCart'])->name('addProductToCart');
}
Controller:
public function addProductToCart(Request $request, Product $product)
{
return redirect()->route('products.index')->with('alert', 'Added product to cart');
}
2
Answers
You need to use the
route()
helper in your test:addProductToCart
is the name of the Method in the Controller, and the name of the Route, but the URL that actually calls that method is/cart/add/{product}
. So, for this to work, you need toPOST
to that URL.You can do that in a number of different ways:
You also need to define
$product
in your Test for this to work, something like:So altogether, your Test would look like this: