Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

pnwpixel's avatar

Test fails on faked PDF upload and accompanying form data

Hello everyone. I am stumped as to why this test fails to pass validation. We are using a dedicated request class to handle the validation. In real world use, this validation logic doesn't throw any errors. Here is the validation logic:

public function rules()
    {
        return [
            'file' => 'required|file|mimes:pdf',
            'type' => 'required|string',
            'agency_id' => 'nullable|exists:agencies,id',
            'exportable' => 'nullable|boolean',
            'restricted' => 'nullable|boolean',
        ];
    }
    public function messages()
    {
        return [
            'file.required' => 'A file is required.',
            'file.file' => 'The file must be a valid file.',
            'file.mimes' => 'The file must be a PDF.',
            'type.required' => 'The type field is required.',
            'type.string' => 'The type must be a string.',            
            'agency_id.exists' => 'The selected agency ID is invalid.',
        ];
    }

Here is the test logic:

$user = User::factory()->create([
      'role_id' => Role::where('name', 'admin')->first()->id,
]);

$file = UploadedFile::fake()->create(
    'document.pdf', 200, 'application/pdf'
);

$data =  [   
     'file' => $file,         
     'type' => 'memo',
     'agency_id' => 1,
     'exportable' => false,
     'restricted' => true,
];
        
$response = $this->actingAs($user)->post(route('documents.store', $data));

$response->assertStatus(200);

I have a dd of the $data array which shows that the faked PDF generated as planned.

And finally, here is the error I am getting from the validator when I run the test. It appears to be not accepting the PDF:

 FAILED  Tests\Feature\DocumentsTest > uploads as admin                                                                                                                   
  Expected response status code [200] but received 302.
Failed asserting that 302 is identical to 200.

The following errors occurred during the last request:

The file must be a valid file.
The file must be a PDF.

  at tests/Feature/DocumentsTest.php:36
     32▕         ];
     33▕         
     34▕         $response = $this->actingAs($user)->post(route('documents.store', $data));
     35▕ 
  ➜  36▕         $response->assertStatus(200);
     37▕     }
     38▕ }
     39▕ 
0 likes
2 replies
pnwpixel's avatar

@jj15 Thank you for that! And yea, that is such a minor change to what I had that there was no way I would have guessed that one.

1 like

Please or to participate in this conversation.