Writing tests for functions that store files

Jan 28, 2022

You might have a function that generates a pdf, stores an attachment, or uploads an image.

But have do you test that the file is getting created without accessing the real storage?

This is actually very easy with the Storage::fake() method. This method creates a fake disk that you can use for testing.

Here is an example of how you would use it:


namespace Tests\Feature;

use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class ExampleTest extends TestCase
    public function test_csv_file_is_created()

        // creates a file called allusers.csv in the 'files' disk


In between the parenthesis, you should set the disk name that you are using in your function, in this case, files, then you can call your function, finally, you can check if the file exists with:


(replacing $disk and $filename with your values of course)

This will make sure that your real disk is never touched and you can be confident that your function works correctly.