VertexBuffer's avatar

Mocking a file in a Storage for a PHPUnit test?

I'm writing a test for one of my Form's store methods, and basically I have a file upload with it. I upload the file via ajax into a temp directory on the server and then when the form is submitted, I transfer it from temp into s3 storage.

I'm having some issues mocking this for my test. I was hoping someone could provide an example of how I could create a temp image file in my temp Storage?

Contents of the image file don't matter so it can just be an empty image. I've tried creating one myself but the code is relatively messy and it's still causing errors in the test.

0 likes
2 replies
alanholmes's avatar

@zyxxyzyxz

You can use Illuminate\Http\Testing\File to simulate creating a file for upload

And you can use Storage::fake(DRIVER) to fake the upload, so that you can assert that the file has been uploaded. This will upload to /storage/framework/testing/disks/DRIVER

       Storage::fake('public');

       $logo = File::image('logo.png', 400, 100);

        $response = $this->actingAs($user)
                         ->putJson('/route', [
                              'logo' => $logo,
                         ]);

      $this->assertTrue(file_exists('path/to/saved/file'));
2 likes
ronon's avatar
ronon
Best Answer
Level 9

You could also use

$file = UploadedFile::fake()->create('image.jpg')
        ->storeAs('app/images', newfilename.jpg)');

With this you could also create any kind of formats like pdf etc.

1 like

Please or to participate in this conversation.