首页 > 解决方案 > 无法在路径中找到文件。无法断言 false 为 true

问题描述

我编写了一个测试来检查用户是否能够上传文件。我public用作我的模拟磁盘。这是我的测试:

public function testUserCanUploadFile()
    {
        $this->withoutExceptionHandling();
        $this->signIn();

        Storage::fake('/public'); //Mock a disk
        $file = UploadedFile::fake()->image('test.jpg'); //Upload a fake image.

        $assortmentAttributes = Assortment::factory()->raw(); // Use the assortment factory.
        $assortmentAttributes['image'] = $file; // Add a additional field in the assortment factory.

        $this->post(route('assortments.store'), $assortmentAttributes)->assertRedirect(); // Post the fields to the assortmentcontroller store method.
        Storage::disk('/public')->assertExists($file); // Check if the field exists.

    }

我还在我的控制器中编写了确保文件被保存的代码。这是我的控制器中的代码:

 public function store(Request $request)
    {     
Assortment::create([
             'file' => $request->file('image')->store('file', '/public'),
             'user_id' => $user->id,
             'category_id' => $assortment->category->id,
             'title' => $assortment->title,
             'description' => $assortment->description
         ]);
 
         if ($request->wantsJson()) {
             return response([], 204);
        }

        return redirect()->route('assortments.show', $assortment->slug)
                        ->with('success','Verzameling is succesvol aangemaakt.');

        
    }

当我运行测试时,我得到:Unable to find a file at path. Failed asserting that false is true.我知道这是因为控制器生成了另一个随机文件,然后是我在测试中想要的那个。但是我该如何解决这个问题?我不知道。

我也用assertExist($file->hashName())在我的测试中。但我删除了它,因为它给出了同样的错误。

我该如何解决这个错误?

标签: phplaravel

解决方案


我认为问题是:

'file' => $request->file('image')->store('file', '/public')

store() 函数的第一个参数是路径,第二个是磁盘。因此,您的文件必须保存在 中/file/test.jpg,但您的测试正在尝试查找/test.jpg


推荐阅读