Testing File uploads in Symfony2

johnwards picture johnwards · Aug 2, 2011 · Viewed 16.8k times · Source

In the Symfony2 documentation it gives the simple example of:

$client->request('POST', '/submit', array('name' => 'Fabien'), array('photo' => '/path/to/photo'));

To simulate a file upload.

However in all my tests I am getting nothing in the $request object in the app and nothing in the $_FILES array.

Here is a simple WebTestCase which is failing. It is self contained and tests the request that the $client constructs based on the parameters you pass in. It's not testing the app.

class UploadTest extends WebTestCase {

    public function testNewPhotos() {
        $client = $this->createClient();
        $client->request(
            'POST', 
            '/submit', 
            array('name' => 'Fabien'), 
            array('photo' => __FILE__)
        );

        $this->assertEquals(1, count($client->getRequest()->files->all()));
    }
}

Just to be clear. This is not a question about how to do file uploads, that I can do. It is about how to test them in Symfony2.

Edit

I'm convinced I'm doing it right. So I've created a test for the Framework and made a pull request. https://github.com/symfony/symfony/pull/1891

Answer

johnwards picture johnwards · Apr 16, 2012

This was an error in the documentation.

Fixed here:

use Symfony\Component\HttpFoundation\File\UploadedFile;

$photo = new UploadedFile('/path/to/photo.jpg', 'photo.jpg', 'image/jpeg', 123);
// or
$photo = array('tmp_name' => '/path/to/photo.jpg', 'name' => 'photo.jpg', 'type' => 'image/jpeg', 'size' => 123, 'error' => UPLOAD_ERR_OK);

$client = static::createClient();
$client->request('POST', '/submit', array('name' => 'Fabien'), array('photo' => $photo));

Documentation here