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

流过昼夜 提交于 2020-12-03 21:44:12

问题


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


回答1:


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());


来源:https://stackoverflow.com/questions/59592101/how-to-fake-image-upload-for-testing-with-intervention-image-package-using-larav

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!