Tom
#fileupload #test #pest
I have this FileUpload field:
and this test:
However, the test fails as the model retains the old filename. Has anyone solved this before?
Forms\Components\FileUpload::make('image')
->image()
->directory('images')
Forms\Components\FileUpload::make('image')
->image()
->directory('images')
it('can replace an image', function () {
// Configure
Storage::fake('test');
FileUpload::configureUsing(function (FileUpload $component) {
$component
->preserveFilenames()
->disk('test');
});
// Initial
$filename = fake()->word().'.jpg';
$file = UploadedFile::fake()->image($filename)->storeAs('images', $filename, ['disk' => 'test']);
$recipe = Recipe::factory()->create(['image' => $file]);
expect($recipe->image)->toBe('images/'.$filename);
// Change
$newFilename = fake()->word.'-NEW.jpg';
$newFile = UploadedFile::fake()->image($newFilename);
livewire(EditRecipe::class, ['record' => $recipe->getRouteKey()])
->fillForm([
'title' => $recipe->title,
'description' => $recipe->description,
'image' => [$newFile],
])
->call('save')
->assertHasNoFormErrors();
$recipe->refresh();
// Assert
assertDatabaseHas(Recipe::class, [
'id' => $recipe->id,
'image' => 'images/'.$newFilename,
]);
Storage::disk('test')->assertExists('images/'.$newFilename);
Storage::disk('test')->assertMissing('images/'.$filename);
});
it('can replace an image', function () {
// Configure
Storage::fake('test');
FileUpload::configureUsing(function (FileUpload $component) {
$component
->preserveFilenames()
->disk('test');
});
// Initial
$filename = fake()->word().'.jpg';
$file = UploadedFile::fake()->image($filename)->storeAs('images', $filename, ['disk' => 'test']);
$recipe = Recipe::factory()->create(['image' => $file]);
expect($recipe->image)->toBe('images/'.$filename);
// Change
$newFilename = fake()->word.'-NEW.jpg';
$newFile = UploadedFile::fake()->image($newFilename);
livewire(EditRecipe::class, ['record' => $recipe->getRouteKey()])
->fillForm([
'title' => $recipe->title,
'description' => $recipe->description,
'image' => [$newFile],
])
->call('save')
->assertHasNoFormErrors();
$recipe->refresh();
// Assert
assertDatabaseHas(Recipe::class, [
'id' => $recipe->id,
'image' => 'images/'.$newFilename,
]);
Storage::disk('test')->assertExists('images/'.$newFilename);
Storage::disk('test')->assertMissing('images/'.$filename);
});
7 replies