I have written the following test in Laravel:
public function testUserCanUploadFile()
{
$this->withoutExceptionHandling();
$user = $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_path'] = $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->hashName()); // Check if the field exists.
$this->assertFileExists($user->image_path);
}
I want to check if the file also exists in the database.
In practice, the file upload works just fine. My test however, does not.
When I run my test I get the following error:
TypeError: Argument 1 passed to PHPUnitFrameworkAssert::assertFileExists() must be of the type string, null given
The field is not set on ->nullable()
in my migration. I also did dd($user->image_path)
. This just returns null
.
I also changed:
$assortmentAttributes['image'] = $file; // Add a additional field in the assortment factory.
To:
$assortmentAttributes['image_path'] = $file; // Add a additional field in the assortment factory.
To make sure the field name matches the field name in my assortment migration.
Does anyone know how I can make sure that the file is found in my database field, so that my test finally works?
The code in my store method in my controller:
if ($request->hasFile('image')) {
$image = $request->file('image'); //request the file
$fileName = md5_file($image . microtime()) . '.' . $image->getClientOriginalExtension(); //use md5 for security reasons and get the extension.
$image->storeAs('', $fileName, 'public'); //store the file in the public folder disk.
}
if ($request->wantsJson()) {
return response([], 204);
}
What signIn()
does:
protected function signIn($user = null)
{
$user = $user ?: User::factory()->create();
$this->actingAs($user);
return $user;
}
Greetings,
Parsa
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…