How to fake image upload for testing with Intervention image package using Laravel
Asked Answered
C

1

6

I have a test asserting that images can be uploaded. Here is the code...

// Test

$file = UploadedFile::fake()->image('image_one.jpg');
Storage::fake('public');

$response = $this->post('/api/images', [
'images' => $file
]);

Then in controller i am doing something simpler..

$file->store('images', 'public');

And asserting couple of things. and it works like charm.

But now i need to resize the image using Intervention image package. for that i have a following code:

 Image::make($file)
        ->resize(1200, null)
        ->save(storage_path('app/public/images/' . $file->hashName()));

And in case if directory does not existing i am checking first this and creating one -

if (!Storage::exists('app/public/images/')) {
        Storage::makeDirectory('public/images/', 666, true, true);
         }

Now Test should be green and i will but the issue is that every time i run tests it upload a file into storage directory. Which i don't want. I just need to fake the uploading and not real one.

Any Solution ?

Thanks in advance :)

Candelaria answered 4/1, 2020 at 15:24 Comment(0)
M
3

You need to store your file using the Storage facade. Storage::putAs does not work because it does not accept intervention image class. However you can you use Storage::put:

$file = UploadedFile::fake()->image('image_one.jpg');
Storage::fake('public');

// Somewhere in your controller
$image = Image::make($file)
        ->resize(1200, null)
        ->encode('jpg', 80);

Storage::disk('public')->put('images/' . $file->hashName(), $image);

// back in your test
Storage::disk('public')->assertExists('images/' . $file->hashName());
Mulatto answered 28/5, 2020 at 22:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.