Hey, my book is finally available. Find it here.  Eloquent Beyond The Basics!

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:

<?php

namespace Tests\Feature;

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

class ExampleTest extends TestCase
{
    public function test_csv_file_is_created()
    {
        Storage::fake('files');

        // creates a file called allusers.csv in the 'files' disk
        GenerateAllUsersCsv::execute(); 

        Storage::disk('files')->assertExists('allusers.csv');
    }
}

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:

Storage::disk($disk)->assertExists($filename);

(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.