ssquare's avatar

Laravel image uploaded successfully test failed

This is my store method

  DB::transaction(function () use ($request) {
      $imageName = LocalHubHelper::renameImageFileUpload($request->file('image'));
      $request->file('image')->move(public_path('storage/uploads/flyers'), $imageName);
      Flyer::create([
          'title'              => $request->input('title'),
          'description'        => $request->input('description'),
          'image'              => $imageName,
          'order'              => $request->input('order'),
          'button_text'        => $request->input('button_text'),
          'button_link'        => $request->input('button_link'),
          'post_id'            => $request->input('post_id'),
      ]);
  });

and this is my factory

  public function definition()
  {
      return [
          'title'             => $this->faker->words(5,true),
          'description'       => $this->faker->realText(50),
          'order'             => 1,
          'post_id'           => Post::factory()->create()->id,
          'button_text'       => null,
          'button_link'       => '#',
          'image'             => UploadedFile::fake()->image('file.png', 250, 150),
          'created_at'        => now(),
          'updated_at'        => now(),
      ];
  }

and this is my test

    public function test_flyer_image_uploaded_successfully()
    {
        $this->signIn();
        $this->withoutExceptionHandling();
        Storage::fake('local');
        $file = UploadedFile::fake()->image('file.png', 250, 150);
        $attributes =  Flyer::factory()->raw(['image' => $file]);
        $response = $this->post($this->endPoint,$attributes)
            ->assertStatus(302);
        $imageName = Flyer::latest()->first()->image;
        Storage::disk('local')->assertExists("public/uploads/flyers/".$imageName);
    }

and this is the failed message

1) Tests\Feature\FlyerTest::test_flyer_image_uploaded_successfully
Unable to find a file at path [public/uploads/flyers/file_20210910.png].
Failed asserting that false is true.

but if I check storage/app/public/uploads/flyers then there is a file with this name. Am I asserting in different path?

0 likes
2 replies
kevinbui's avatar
kevinbui
Best Answer
Level 41

The $request->file('image') part will be an instance of Illuminate\Http\UploadedFile.

I have checked the source code for that class. When you use the store or storeAs methods, the file will be saved via a disk instance. The file will be saved differently if you use the move method.

As I understand, that's why the assertion fails, because it is made from a fake disk.

So instead of using the move method, what about simply using the store or storeAs methods, which pretty much do the same thing? You got the file from the request so you don't really have to move it anywhere.

Please or to participate in this conversation.