Ashraam
199
1
Testing

Testing file upload and resizing won't work

Posted 3 months ago by Ashraam

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 ?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.