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.
array:5 [
"file" => Illuminate\Http\Testing\File^ {#2759
+name: "document.pdf"
+tempFile: stream resource {@1063
timed_out: false
blocked: true
eof: false
wrapper_type: "plainfile"
stream_type: "STDIO"
mode: "r+b"
unread_bytes: 0
seekable: true
uri: "/tmp/phptFIGpD"
options: []
}
+sizeToReport: 204800
+mimeTypeToReport: "application/pdf"
-originalName: "document.pdf"
-mimeType: "application/pdf"
-error: 0
-originalPath: "document.pdf"
-test: true
#hashName: null
name: "document.pdf"
tempFile: stream resource @1063
sizeToReport: 204800
mimeTypeToReport: "application/pdf"
path: "/tmp"
filename: "phptFIGpD"
basename: "phptFIGpD"
pathname: "/tmp/phptFIGpD"
extension: ""
realPath: "/tmp/phptFIGpD"
aTime: 2025-02-04 18:27:44
mTime: 2025-02-04 18:27:44
cTime: 2025-02-04 18:27:44
inode: 33652849
size: 204800
perms: 0100600
owner: 501
group: 20
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
}
"type" => "memo"
"agency_id" => 1
"exportable" => false
"restricted" => true
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▕