artka54's avatar

Testing image upload but it fails when I add validation rule

I am testing image upload via PHPunit by calling a route (/admin/articles) which uses a controller (ArticleController) to upload an image.

        $data = [
            'heroImage' => UploadedFile::fake()->image('test_image.jpg')
        ];
        
        // Call a controller via route
        $response = $this->actingAs($user)->call('POST', '/admin/articles', $data);

In my ArticleController I have a validation rule

        $this->validate($request, [
            'heroImage' => 'image|mimes:jpg,png'
        ]);

When I run tests without the validation rule they pass, but when I add the validation rule they fail.

What am I doing wrong?

Thank you!

0 likes
10 replies
artka54's avatar

No I am not using a form but a phpunit test which calls a route to post the image to controller. So the problem does not lie in the form.

The test passes when I remove mimes:jpg,png from the validator.

I suspect the reason behind is that 'heroImage' => UploadedFile::fake()->image('test_image.jpg') can not fake mime types?

Thanks

2 likes
artka54's avatar

Yes but I do not want to make stubs but leverage UploadedFile::fake()->image() method instead.

2 likes
artka54's avatar

@andreich1980 Nope, I am just uncommenting the rule, but I guess this issue needs to be dealt for seamless CI, but I am not there yet.

sutherland's avatar
Level 28

Either change it to 'image|mimes:jpeg,png' or 'image|mimetypes:image/jpeg,image/png'

3 likes
andreich1980's avatar

@sutherland I just tried image rule and it worked. Thanks! But only with mimetypes:image/jpeg,image/png. This mimes:jpeg,png still doesn't work :(

@artka54 would you choose the @sutherland 's answer as the best?

artka54's avatar

All right so for me the problem was that I left out the letter "e" from the "jpg". If I use "jpeg" then both variants work.

Although I fake .jpg file the validation rule has to have 'jpeg'

@andreich1980 could it be the case with you as well?

3 likes
sutherland's avatar

@andreich1980 @artka54 I think using mimetypes:image/jpeg,image/png is the best solution, because the mime type will always be the same regardless of file extension. I think when using image|mimes:jpeg,png Laravel will try to infer the mime type, which should work, but just isn't as explicit.

3 likes

Please or to participate in this conversation.