CLab's avatar
Level 3

Writing test for function to store files

I have a function in a trait which stores an attachment to a Google Cloud Storage bucket like:

  public function storeFiles($type, $id, $attachments)
  {
    $folder = $type . '/' . $id;
    $disk = \Storage::disk('gcs');

    if (!empty($attachments)) {
      $output = [];
      foreach ($attachments as $attachment) {
        $file = $attachment['file'];
        $filename = $file->getClientOriginalName();
        $file->storeAs($folder, $filename);
        array_push($output, [
          'name' => $filename,
          'notes' => $attachment['notes']
        ]);
      }

      return $output;
    }
  }

This can be called for example like:

$this->storeFiles('avatars', $user->id, $request->all()['attachments'])

I want to test this function, and I am reviewing the docs from https://laravel.com/docs/8.x/http-tests#testing-file-uploads

Q1. Should I write a unit test or a feature test?

  • I am guessing Feature test

Q2. Do I have to edit the phpUnit.xml file to use local storage or is there a way to simulate the cloud storage bucket?

  • I am guessing I can use Storage::fake('avatars') to produce a "fake" local storage, but I worry that since I specify the disk in the storeFiles function, it may supersede it?
0 likes
4 replies
Nakov's avatar
Nakov
Best Answer
Level 73

It is a Feature test, and you should use Storage::fake('gcs') to override the disk driver.

1 like
CLab's avatar
Level 3

@Nakov Thanks Nakov- this will not affect the actual bucket on the cloud right?

Nakov's avatar

@CLab Based on what I see it shouldn't. But I guess you are not using the production bucket for local development as well, so you should have a separate one so that when running your tests you don't do anything by mistake. I don't know if in some of your tests you'll forget to add the Storage fake..

Here is an example of S3 test, which is the same for you, except you are using GCS:

https://freek.dev/1295-testing-simple-s3-uploads-with-randomized-file-names-in-laravel

Please or to participate in this conversation.