CaptchaBundle icon indicating copy to clipboard operation
CaptchaBundle copied to clipboard

How to test Captcha

Open engharb opened this issue 7 years ago • 2 comments

Hi,

I am running PhpUnit test but I do not know how to set the captcha value in the form before submitting the form?

May I can read the Symfony session but later the session will no longer valid/stored.

Any idea?

engharb avatar Sep 17 '18 14:09 engharb

You should disable it in test environment.

# config/packages/test/gregwar_captcha.yaml
gregwar_captcha:
    disabled: true

Seb33300 avatar Jun 04 '19 05:06 Seb33300

Wouldn't be better to test getting the phrase from the session in the container? This way the integration of the captcha with your forms could be tested too.

This is how I do it in a contact form:

$crawler = $client->request(Request::METHOD_GET, '/contact');

self::assertStatusCodeEquals(Response::HTTP_OK, $client);

$session = static::$kernel->getContainer()->get('session');
$captcha = $session->get('_captcha_captcha');

$form = $crawler->selectButton(self::SEND_MESSAGE_LABEL)->form();
$form->get('contact_request[name]')->setValue('John Smith');
$form->get('contact_request[email]')->setValue('[email protected]');
$form->get('contact_request[subject]')->setValue('A test email');
$form->get('contact_request[body]')->setValue('This email is sent from a test');
$form->get('contact_request[captcha]')->setValue($captcha['phrase']);
$client->submit($form);

irozgar avatar Aug 19 '20 15:08 irozgar