AR's avatar
Level 7

Testing file upload fails but the functionality works in the browser

I have a controller that saves the product and then saves the photos for that. I have also written a test for creating the product. When I manually add the product everything works fine and I get what I want But the test fails all the time and also saves the fake image in photos/p directory all the time.

Here is my controller:

public function store(Request $request, $shop)
    {
        $shop = Shop::findByUrl($shop);

        $product = Product::create([
            'name' => request('name'),
            'description' => request('description'),
            'price' => bcmul(request('price'), 100),
            'shop_id' => $shop->id
        ]);

        foreach (request('photos') as $photo) {
            $path = $photo->store('photos/p', 'public');

            ProductPhoto::create([
                'product_id' => $product->id,
                'path' => $path
            ]);
        }

        return redirect($product->path);
    }

Here is my Test:

/** @test */
    public function an_authenticated_user_can_create_a_product()
    {
        $user = factory(User::class)->create();

        $shop = factory(Shop::class)->create([
            'user_id' => $user->id
        ]);

        Storage::fake('photos');

        $response = $this->actingAs($user)
                        ->post($shop->path() . '/products', $this->validParams([
                            'photos' => [
                                    UploadedFile::fake()->image('123.jpg')
                                ]
                        ]));

        $this->assertCount(1, $shop->products);
        $this->get($response->headers->get('Location'))
            ->assertSee('CupCake')
            ->assertSee('The best cupcake ever')
            ->assertSee('USD 38.50');
        Storage::disk('photos')->assertExists('123.jpg');
    }

Please Advice

0 likes
0 replies

Please or to participate in this conversation.