Testing dynamic file uploads with Laravel

David Carr

Laravel Framework Tutorials

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

 

 

Fathom Analytics $10 discount on your first invoice using this link

David Carr - Laravel Developer

Hi, I’m David Carr

A Senior Developer at Vivedia
I love to use the TALL stack (Tailwind CSS, Alpine.js, Laravel, and Laravel Livewire)

I enjoy writing tutorials and working on Open Source packages.

I also write books. I'm writing a new book Laravel Testing Cookbook, This book focuses on testing coving both PestPHP and PHPUnit.

Sponsor me on GitHub

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Laravel Testing Cookbook

Help support the blog so that I can continue creating new content!

Fathom Analytics $10 discount on your first invoice using this link

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2006 - 2023 DC Blog. All code MIT license. All rights reserved.