DavidBuchukuri's avatar

Image upload can't pass validation inside tests

when I'm creating a fake image and sending it via post request, there is a validation error Image field must be an image type. I am validating with a form request. My validation rule looks like this.


class MovieStoreRequest extends FormRequest
{
    public function rules()
    {
        return [
            'image'  => ['required', 'image'],
        ];
    }

    public function messages()
    {
        return[
            'image.required' => 'Image_field_is_required',
            'image.image' => 'Image field must be an image type',
        ];
    }

Also I tried to change image rule to mimes:jpeg,png,svg,jpg, but result was the same. here Is my code in the test.

  /** @test */
    public function can_store_a_movie()
    {
        Storage::fake('public');
        $this->signIn();
        $movie = $this->generateMovie();

        $file = UploadedFile::fake()->image('movie.png');
        $movie['image'] = $file;

        $resp = $this->post(route('movie.store', $movie))->assertStatus(201);
    }

I also tried to create an image like this. UploadedFile::fake()->create('movie.png', 100), but again, result is the same.

btw, I wrote another test, where I uploaded fake image and it worked without validation. I even asserted it against Storage::disk and that test was all green.

0 likes
3 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

You need to move it to the post() method, not route() method

//before
$resp = $this->post(route('movie.store', $movie))->assertStatus(201);
//after
$resp = $this->post(route('movie.store'), $movie)->assertStatus(201);
2 likes

Please or to participate in this conversation.