Ashraam's avatar
Level 41

Testing file upload and resizing won't work

Hi everyone,

I'm learning to develop using the TDD way and I'm facing this problem I can't solve.

I'm uploading an image which is resized and store in database.

When I'm doing it manually (using my browser like a regular user) it works, but the test fail.

Here is my controller:

public function store(Product $product)
    {
        //$name = request('image')->store('products', 'public');

        $name = str_random(50).'.jpg';
        $path = storage_path('app/public/products/'.$name);

        $image = Image::make(request('image'));
        $image->fit(400, 400);
        $image->save($path);

        $product->photos()->save(new Photo([
            'name' => $name
        ]));

        return redirect($product->adminPath());
    }

and here is my test

public function a_user_can_add_photos_to_the_product()
    {
        $this->withoutExceptionHandling();
        $this->signIn();

        $product = ProductFactory::create();

        Storage::fake('public');

        $this->post($product->adminPath('/photos'), [
            'image' => UploadedFile::fake()->image('photo.jpg')
        ])->assertRedirect($product->adminPath());

        $product->load(['photos']);

        tap($product->photos->first(), function ($photo) {
            $this->assertInstanceOf('App\Photo', $photo);

            Storage::disk('public')->assertExists($photo->name);
        });

        $this->assertEquals(1, $product->photos->count());
    }

At this point the test will fail, but If i comment the resize part and use the store method on the request like this:

Tests\Feature\ManageProductPhotoTest::a_user_can_add_photos_to_the_product
Unable to find a file at path [pJ1Zd19XT0aF9fc5W1famc3n7WwxBt3L9MDB0yRJNlVYcWkMwk.jpg].
Failed asserting that false is true.
public function store(Product $product)
    {
        $name = request('image')->store('products', 'public');

        /*$name = str_random(50).'.jpg';
        $path = storage_path('app/public/products/'.$name);

        $image = Image::make(request('image'));
        $image->fit(400, 400);
        $image->save($path);*/

        $product->photos()->save(new Photo([
            'name' => $name
        ]));

        return redirect($product->adminPath());
    }

The test passes.

How can I solve this issue ?

0 likes
1 reply
Nash's avatar

The "resize part" is saving the image to the real storage while the fake storage used by the Storage facade is actually located under storage/framework/testing/disks. Use the store method on the request, Laravel's Storage facade or change the $path depending on the environment. Something like this should also work:

// $image = Image::make(), fit(), etc...

Storage::put($path, (string) $image->encode('jpg', 100));

Please or to participate in this conversation.