Tutorials | Laravel Framework

David Carr

Testing dynamic file uploads with Laravel

When working with file uploads where the file name is generated, how do you know what the file name is and then test it exists in a test.

First in a controller doing a file upload with a store call which will store the file into a files folder in the public disk, if you don't need to specify the desk the leave off the second param.

$path = $request->file('name')->store(
    'files',
    'public'
);

//when no disk is required

$path = $request->file('name')->store('files');

Now this method would return the $path as its return.

Then In a test use the storage fake which tells Laravel to fake a file upload

Storage::fake('files');

To fake an upload you can use:

UploadedFile::fake()->image('avatar.jpg')

 To assert the file exists you can check the file in storage:

Storage::assertExists('files/avator.jpg');

But if the file is stored dynamically you won't know the file name in which case you will need to look inside the response from the test. The response is not JSON but a test response. In order to covert this to json use decodeResponseJson on the response. Then you can use json as normal.

Putting it all together:

test('can upload file', function () {

    Storage::fake('files');

    $response = post('api/v1/file', [
        'name' => UploadedFile::fake()->image('avatar.jpg'),
    ])
        ->assertStatus(201)
        ->assertSessionHasNoErrors();

    $path = $response->decodeResponseJson()['data']['path'];

    Storage::assertExists($path);
});

 

 

The Ultimate Managed Hosting Platform

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2022 DC Blog. All code MIT license. All rights reserved.