coderego's avatar

Testing File Uploads fails at validation

At my wits end here. No idea why this isn't working. Everything works great from the browser, the code allows me to upload videos successfully, and it throws the validation error if no file is provided. This test works fine without the validation rule. What the heck am I missing?

Thank you

controller

    public function store(Request $request)
    {

        $this->validate($request, [
            'channel_id' => 'required|exists:channels,id',
            'title' => 'required',
            'video' => 'required',
            'body' => 'required',
        ]);

        $file = $request->file('video')->store('videos');

        $video = Video::create([
            'user_id' => auth()->id(),
            'channel_id' => request('channel_id'),
            'title' => request('title'),
            'body' => request('body'),
            'path' => $file
        ]);

        return redirect($video->link());
    }

** test **

 function an_authenticated_user_can_create_new_videos()
   {
       $this->signIn();


       $video = make('App\Video');
       $rawVideo = prepareVideoUpload($video);
       

       $response = $this->post('/videos', $rawVideo);


       $this->get($response->headers->get('Location'))
           ->assertSee($video->title);
   }

** factory **

$factory->define(App\Video::class, function($faker)
{

    return [
        'user_id' => function() {
            return factory('App\User')->create()->id;
        },
        'channel_id' => function() {
            return factory('App\Channel')->create()->id;
        },
        'title' => $faker->sentence,
        'body' => $faker->paragraph,
        'path' => 'test.mp4'
    ];
});

helper function

function prepareVideoUpload(\App\Video $video)
{
    $rawVideo = $video->toArray();

    $path  = '/tmp/test.mp4';
    $mimeType = 'video/mp4';
    $file = new \Symfony\Component\HttpFoundation\File\UploadedFile ($path, 'test.mp4', $mimeType, 383631, null, false);


    $rawVideo['video'] = $file;

    return $rawVideo;
}
0 likes
5 replies
ohffs's avatar

...What is actually going wrong?

coderego's avatar

The test is throwing a validation error based on 'video' => 'required',

Time: 2.11 seconds, Memory: 12.00MB

There was 1 error:

1) Tests\Feature\CreateVideosTest::an_authenticated_user_can_create_new_videos
Illuminate\Validation\ValidationException: The given data failed to pass validation.

ohffs's avatar

Have you tried dd'ing the $request in the controller before the validation call? Just to see what's in it?

ohffs's avatar

Not sure - I've seen file upload/validation stuff fail in weird ways if the file is bigger than php is configured for. Try uploading a tiny file maybe just in case?

Other than that - maybe before the validation try storing the file somewhere on disk and seeing what it contains - just to make sure it's actually being passed through?

Please or to participate in this conversation.