Tom
Tom
FFilament
Created by Tom on 1/22/2025 in #❓┊help
#fileupload #test #pest
I have this FileUpload field:
Forms\Components\FileUpload::make('image')
->image()
->directory('images')
Forms\Components\FileUpload::make('image')
->image()
->directory('images')
and this test:
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);
});
However, the test fails as the model retains the old filename. Has anyone solved this before?
7 replies