Changing default disk for testing.

Posted 1 year ago by alhoqbani

I'm trying to build a test for images handling in my application. For the database testing I'm using DatabaseMigrations, so the test persists records in sqlite memory and then discard them after the test.

Is there a way to achieve equivalent results when testing file handling (uploading and deleting files).

Right now I'm using the fake method as suggested per the docs:

        Storage::fake('avatars');

        $response = $this->json('POST', '/avatar', [
            'avatar' => UploadedFile::fake()->image('avatar.jpg')
        ]);

        // Assert the file was stored...
        Storage::disk('avatars')->assertExists('avatar.jpg');

        // Assert a file does not exist...
        Storage::disk('avatars')->assertMissing('missing.jpg');

However in my Image model, i'm overriding the delete() method to delete the file linked to the record:

    public function delete()
    {
        Storage::delete($this->image_path);

        return parent::delete();
    }

When testing this method, it will always fail because this method will delete files only from the default storage, but not from the fake storage ('avatars').

Here is my test:

/** @test */
    public function deleted_image_from_db_will_delete_the_file()
    {
        Storage::fake('avatars');
        $file = UploadedFile::fake()->image('avatar.png');
        $image = Image::fromForm($file);  // Store the image and set image_path;
        $image->product_id = 1;
        $image->save();

        Storage::disk('avatars')->assertExists($image->image_path);
        $image->delete();
        Storage::disk('avatars')->assertMissing($image->image_path);
    }

Is it possible to set the default disk for testing to a fake storage?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.