Search code examples
laravellaravel-factory

How to create a factory with images for testing


I need to create a factory that create images for testing. The factory should create images and save them on storage and after the test everything should be erased.

How can I do that ?

What I am thinking now is to put the fields at null on the factory and then using the afterCreating method to save the images manually but it has to be a better way to do that right ?

What I want to achieve is :

factory(Category::class)->create();

That will generate all images.

$faker->image does not work anymore since LoremPixel (the provider) is really slow or down most of the time.


Solution

  • The cleaner way I found is:

    1. Set the value at null on the factory

      $factory->define(Category::class, function (Faker $faker) {
          return [
              'img' => null,
         ];});
      
    2. Use $factory->afterCreating to override the value and save the image

      $factory->afterCreating(Category::class, function ($category, $faker) {
         $category->img = UploadedFile::fake()->image(uniqid() . '.jpg')->store('categories');
         $category->save();
      });
      
    3. Create a fake storage on test setUp() and reset it on tearDown()

      protected function setUp(): void {parent::setUp();Storage::fake('public');}

      protected function tearDown(): void{ Storage::fake('public'); }

    This solution creates images for testing and remove everything after it.

    (Sorry for code sample, I can't make it indent properly)