Skip to content

Commit

Permalink
Test validating image upload
Browse files Browse the repository at this point in the history
  • Loading branch information
unclexo committed Dec 23, 2022
1 parent adde095 commit 05286dd
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
13 changes: 13 additions & 0 deletions app/Http/Controllers/MediaUploaderController.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,17 @@ public function rename()

return ['path' => $path];
}

public function validateUpload()
{
\request()->validate([
'image' => ['required', 'mimes:jpg,png', 'size:100']
]);

$newImageName = 'you-name-it.jpg';

$path = \request()->file('image')->storeAs('validated', $newImageName, 'public');

return ['path' => $path];
}
}
2 changes: 2 additions & 0 deletions routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,7 @@
Route::post('/upload', 'upload')->name('upload.common');

Route::post('/upload/renamed', 'rename')->name('upload.renamed');

Route::post('/upload/validation', 'validateUpload')->name('upload.validation');
});
});
23 changes: 23 additions & 0 deletions tests/Feature/UploadModuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public function a_user_can_upload_an_image()
'image' => $file = UploadedFile::fake()->image('image-name.jpg'),
]);

// points to "app/public/common" dir
Storage::disk('public')->assertExists('common/' . $file->hashName());
}

Expand All @@ -37,9 +38,31 @@ public function uploaded_image_has_a_new_name()
'image' => $file = UploadedFile::fake()->image($originalName = 'image-name.jpg'),
]);

// points to "app/renamed" dir
Storage::disk('local')
->assertMissing('renamed/' . $originalName)
->assertMissing('renamed/' . $file->hashName())
->assertExists($response->json('path')); // Note this line
}

/** @test */
public function it_can_upload_valid_image()
{
// Uncomment this line to check errors
// $this->withoutExceptionHandling();

$this->actingAs(User::factory()->create());

Storage::fake('public');

$this->post(route('upload.validation'), [
'image' => UploadedFile::fake()->create('video-filename.mp4', 200, 'video/mp4'),
])->assertSessionHasErrors(['image']);

$response = $this->post(route('upload.validation'), [
'image' => UploadedFile::fake()->create('image-name.jpg', 100, 'image/jpeg'),
]);

Storage::disk('public')->assertExists($response->json('path'));
}
}

0 comments on commit 05286dd

Please sign in to comment.