Closed
Description
Description
Now that we got an automatic way to get 422 response code when a form is invalid (see #40799), I think it could be nice to ease testing it.
I'm proposing to add a new method to BrowserKitAssertionsTrait
:
<?php
namespace Symfony\Bundle\FrameworkBundle\Test;
trait BrowserKitAssertionsTrait
{
public static function assertResponseIsUnprocessable(string $message = ''): void
{
self::assertThatForResponse(new ResponseConstraint\ResponseIsUnprocessable(), $message);
}
// ...
}
with relative constraint
<?php
namespace Symfony\Component\HttpFoundation\Test\Constraint;
use PHPUnit\Framework\Constraint\Constraint;
use Symfony\Component\HttpFoundation\Response;
final class ResponseIsUnprocessable extends Constraint
{
/**
* {@inheritdoc}
*/
public function toString(): string
{
return 'is unprocessable';
}
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function matches($response): bool
{
return Response::HTTP_UNPROCESSABLE_ENTITY === $response->getStatusCode();
}
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function failureDescription($response): string
{
return 'the Response '.$this->toString();
}
/**
* @param Response $response
*
* {@inheritdoc}
*/
protected function additionalFailureDescription($response): string
{
return (string) $response;
}
}
Example
Instead of calling self::assertResponseStatusCodeSame(422)
or self::assertResponseStatusCodeSame(Response::HTTP_UNPROCESSABLE_ENTITY)
each time that you want to test for a submitted invali form, you could simply call self::assertResponseIsUnprocessable()