jamesoneill's avatar

Validation always fails when testing file uploads

I am trying to test a file upload action and am struggling to add form validation to it. Without the validation my test passes fine but when I add it the validation always fails. I'm not really sure if I'm doing file upload tests right here so any pointers for what I should be doing would be appreciated.

This is my test:

function can_upload_a_jpeg_image()
{
    $imageStream = Image::canvas(3, 3, '#fff')->stream('jpg');
    $this->disk()->put('test/image.jpg', (string) $imageStream);
    $file = new UploadedFile(base_path('storage/app/test') . '/image.jpg', 'image.jpg');

    $this->assertEquals(0, ImageModel::count());
    $response = $this->post('/admin/image', ['image' => $file], [
            'Accept' => 'application/json'
        ]);

    $response->assertStatus(201);
        $this->assertEquals(1, ImageModel::count());
        $this->assertTrue($this->disk()->exists(md5($imageStream) . '@3x.jpeg'));
        $this->assertTrue($this->disk()->exists(md5($imageStream) . '@2x.jpeg'));
        $this->assertTrue($this->disk()->exists(md5($imageStream) . '@1x.jpeg'));
}

This is the controller action it goes to:

function store() 
{
    $this->validate(request(), [
            'image' => ['required', 'image']
        ]);
    
    $image = Image::make(request()->file('image'));
        $image->backup();
        $fileName = md5($image->stream());
        $fileExtension = request()->file('image')->extension();
        Storage::put("{$fileName}@3x.{$fileExtension}", (string) $image->stream());

        $image->resize(ceil($image->width() * 0.66), null, function ($constraint) {
            $constraint->aspectRatio();
        });
        Storage::put("{$fileName}@2x.{$fileExtension}", (string) $image->stream());
        $image->reset();

        $image->resize(ceil($image->width() * 0.33), null, function ($constraint) {
            $constraint->aspectRatio();
        });
        Storage::put("{$fileName}@1x.{$fileExtension}", (string) $image->stream());

        $imageModel = ImageModel::create([
            'name' => $fileName, 'url' => "{$fileName}@1x.{$fileExtension}"
        ]);

        return response()->json($imageModel, 201);
}
0 likes
1 reply
jamesoneill's avatar
jamesoneill
OP
Best Answer
Level 8

Solved it myself.

Turns out I was missing the $test parameter in UploadedFile's constructor. Once I added that the test worked fine.

Please or to participate in this conversation.