Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 :)

like image 239
Rakesh K Avatar asked Jan 04 '20 15:01

Rakesh K


1 Answers

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());
like image 51
Adam Avatar answered Nov 19 '22 04:11

Adam