12

I am new to laravel, I can run successfully my file uploader, it uploads successfully my file, but the unit test fails, here is my code:

UploadTest.php

public function testUploadFile()
{
    $fileSize = 1024; // 1mb
    $fileName = 'file.txt';

    Storage::fake('files');
    $response = $this->json('POST', '/webservice/upload', [
        'file' => UploadedFile::fake()->create($fileName, $fileSize)
    ]);

    Storage::disk('files')->assertExists($fileName);
    Storage::disk('files')->assertMissing($fileName);
}

FileUploadController

public function upload(Request $request)
{
    $file = $request->file('file');
    if ($file == null) {
      return view('fileupload', 
        ['submitClickedMsg' => "Please select a file to upload."]);
    }

    $path = $file->storeAs('files', $file->getClientOriginalName(), 'local');
    return response()->json([
      'path' => $path
    ]);
}

filesystem.php

'disks' => [
        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],
        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
        ],
    ],

Help is greatly appreciated, thanks.

NikiC
  • 100,734
  • 37
  • 191
  • 225
Nickan
  • 313
  • 2
  • 11

1 Answers1

25

With Storage::fake('files') you would fake a so called disk named 'files'. In your filesystems.php is no disk declared named 'files'.

In your FileUploadController you are saving to the subdirectory 'files' on your 'local' disk, so for making your test work, just fake this disk:

Storage::fake('local');

Also use this disk then for the assertions:

Storage::disk('local')->assertExists('files/' . $fileName);

In the testing environment the path will be storage/framework/testing/disks and not below storage/app directly.

Corben
  • 414
  • 4
  • 7