Testing File Uploads With Laravel

Tutorials

March 3rd, 2017

laravel-testing-file-uploads.png

Laravel now includes a new system for testing file uploads through two new fake methods, one on the UploadFile class and another on the Storage facade.

As the documentation shows here is a full test showing it in use:

1<?php
2
3namespace Tests\Feature;
4
5use Tests\TestCase;
6use Illuminate\Http\UploadedFile;
7use Illuminate\Support\Facades\Storage;
8use Illuminate\Foundation\Testing\WithoutMiddleware;
9use Illuminate\Foundation\Testing\DatabaseMigrations;
10use Illuminate\Foundation\Testing\DatabaseTransactions;
11
12class ExampleTest extends TestCase
13{
14 public function testAvatarUpload()
15 {
16 Storage::fake('avatars');
17
18 $response = $this->json('POST', '/avatar', [
19 'avatar' => UploadedFile::fake()->image('avatar.jpg')
20 ]);
21
22 // Assert the file was stored...
23 Storage::disk('avatars')->assertExists('avatar.jpg');
24
25 // Assert a file does not exist...
26 Storage::disk('avatars')->assertMissing('missing.jpg');
27 }
28}

You can also customize the files width, height, and size for testing validation:

1UploadedFile::fake()->image('avatar.jpg', $width, $height)->size(100);

Or create other types of files like PDF’s:

1UploadedFile::fake()->create('document.pdf', $sizeInKilobytes);

This feature is in the latest Laravel release and you can find out more details in the official documentation.

Filed in:

Eric L. Barnes

Eric is the creator of Laravel News and has been covering Laravel since 2012.