Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.6 Testing File Uploads (Unable to find a file at path [file.txt])

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.

like image 457
Nickan Avatar asked Mar 08 '18 06:03

Nickan


1 Answers

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.

like image 128
Corben Avatar answered Nov 01 '22 05:11

Corben