gbalduzzi gbalduzzi - 1 year ago 70
PHP Question

Don't move original file while testing Laravel 5.2

I'm trying to write tests for a POST callback which receives a file.

The Controller moves the images to the desired location with this function:

$request->file('image')->move(env('IMG_DIR'), $filename);

env('IMG_DIR') is different in testing and in local environment and it works really well.

My Test is the following:

$file = new UploadedFile(base_path() . 'tests/file/test_img.png', 'test.png', 'png', null, null, true);

$this->call('POST', '/endpoint', null, ['user-jwt' => env('CU_JWT')], ['image' => $file])

The upload works great and the image is moved correctly, tests are successful.

The problem is that everytime i run the test, the image i use for testing (
) is moved away and disappear from the directory.
Is there a way to tell PHPUnit/Laravel that the upload must only be faked and not really move the original image?

Answer Source

In your dev environment, make a copy of the image:

$originalImagePath = base_path() . 'tests/file/test_img.png'; 
$copyImagePath = base_path() . 'tests/file/test_img_copy.png';

File::copy($originalImagePath, $copyImagePath) 

Then work with the copied image only

$file = new UploadedFile($copyImagePath, 'test.png', 'png', null, null, true); // etc.

This way the copied image leaves your image directory and you run your test, and everything ends up the same way it started.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download