Search code examples
symfonyphpunitx-http-method-override

Symfony2 & phpunit: enable method override


I just started on a Symfony2 project. The CRUD generation tool created a default controller and functional test, which I'm modifying to suit my needs. The edit-form generated by the controller creates the following HTML:

<form action="/app_dev.php/invoice/7" method="post" >
    <input type="hidden" name="_method" value="PUT" />
    <!-- ... -->
</form>

I like the approach of overriding the HTTP method, because it enables me to create semantic routes in my application. Now I'm trying to test this form with a functional test, using the following:

$crawler = $client->click($crawler->selectLink('Edit')->link());
$form = $crawler->selectButton('Edit')->form(array(
    '_method' => 'PUT',
    // ...
));

$client->submit($form);
$this->assertEquals(302, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code for POST /invoice/<id>/edit");

When I execute the tests by running phpunit -c /app, my tests fails because the status code is 405 instead of the expected 302.

With a bit of debugging I found out that the response of is a MethodNotAllowedHttpException. Appearantly, when running the test through PHPUnit, the method overriding (which internally maps a POST request in combination with _method=PUT param to a PUT request) doesn't take place.

That said, my question is: when executing my PHPUnit tests, why doesn't symfony recongize the overwritten method?


Solution

  • The second argument of form method is a http method. So try this:

    $form = $crawler->selectButton('Edit')->form(array(
        // ...
    ), 'PUT');