slewis's avatar

File upload fails validation in tests when creating fake file

Similar to the issue described here but when validating other file types. In my case I am trying to validate pdf files. The rule passes validation in live testing, but fails when creating a fake file using UploadedFile::fake()->create('file.pdf')

Request Class

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'pdf' => ['required', 'file', 'mimes:pdf'],
        ];
    }

Test Class

        $pdf = UploadedFile::fake()->create('file.pdf');

        $this->json('POST', route('assets.verify', ['pdf' => $pdf]))->dump();

errors

"pdf": array:2 [
      0 => "The pdf must be a file."
      1 => "The pdf must be a file of type: pdf."
    ]

I also tried setting the filesize in the create() method, and setting the mime type to application\pdf

0 likes
5 replies
jlrdw's avatar

Does a real upload work? If yes why worry about a test.

jlrdw's avatar

When I did java years ago at a trucking co, I had real site and a duplicate real site, just different url.

I ran everything as if for real, things like:

  • a multi pick drop load
  • driver settlements (pay)
  • billing
  • dispatch
  • check calls
  • etc

To me real testing is better than mock testing. You are still testing, but for real.

If mock test was so great, no framework would never have an issue on Github.

SimplyCorey's avatar
Level 6

Your test class is trying to pass in the file attributes as a query of your route and not actually uploading the file.

        $pdf = UploadedFile::fake()->create('file.pdf');

        $this->json('POST', route('assets.verify'), ['pdf' => $pdf]);

Notice the route() was closed, then your file is passed in the request.

4 likes

Please or to participate in this conversation.