Testing File Uploads In Laravel PHP Unit

My Experience writing tests for file upload functionality with PHP unit.

The Scenario

In PHP unit when we would like to test the upload functionality of our site it is best (in most cases) to not actually upload anything to anywhere and instead use Laravels helpful Facade mockery capabilities.

The Code

// The name of the drive to use, for example profile pictures will not be placed in the same place as post images
Storage::fake('profile-pictures');

// make a fake file using Laravel's facade mockery interface
// Param1: name of file, Param 2: size in kbs
$profileImage = UploadedFile::fake()->create('test-user.jpg', 36)

// Make a http request to the endpoint with the fake file as a parameter
$this->post('/profile/update', [
    'name' => 'joe Bloggs',
    'location' => 'Leeds, UK',
    'profile_image' => $profileImage
])->assertStatus(302);

The controller method should contain something like

$profileImageName = $request->file('profile_image')->name;
$profileImageContents = $request->file('profile_image');
$user->profile_image = Storage::disk('profile-images')->put($profileImageName, $profileImageContents);

// visit the profile page and make sure the profile picture has updated our new one
$this->get('profiles/username')->assertSee('test-user.jpg');

Recap

To recap we create a fake disk to store our profile pictures on. Created a fake UploadFile object setting the name, and the size of it. We then posted this to our application. Finally we navigated to the profile page and looked for the source of our newly uploaded image