skip to Main Content

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


  1. You need to use the route() helper in your test:

        public function test_user_can_add_product_to_cart()
        {
            $response = $this->post(route('addProductToCart'), ['quantity' => 4], [
                Product::first(),
            ]);
    
            ...
        }
    
    Login or Signup to reply.
  2. 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 to POST to that URL.

    You can do that in a number of different ways:

    $this->post("/cart/add/{$product->id}", ['quantity' => 4]);
    
    // OR
    
    $this->post(url("/cart/add/{$product->id}"), ['quantity' => 4]);
    
    // OR
    
    $this->post(route('addProductToCart', $product), ['quantity' => 4]);
    

    You also need to define $product in your Test for this to work, something like:

    $product = Product::factory()->create();
    
    // OR
    
    $product = Product::first();
    

    So altogether, your Test would look like this:

    public function test_user_can_add_product_to_cart() {
      $user = User::factory()->create();
      $product = Product::factory()->create();
    
      $this->actingAs($user);
      $response = $this->post(route('addProductToCart', $product), ['quantity' => 4]);
    
      $response->assertRedirect('/products');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search