Skip to content

Commit

Permalink
Added seeFormErrorMessage function (#50)
Browse files Browse the repository at this point in the history
  • Loading branch information
TavoNiievez authored Nov 24, 2020
1 parent 0f669ca commit 0db0214
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions src/Codeception/Module/Symfony.php
Original file line number Diff line number Diff line change
Expand Up @@ -1108,6 +1108,65 @@ public function seeCurrentActionIs(string $action)
$this->fail("Action '$action' does not exist");
}

/**
* Verifies that a form field has an error.
* You can specify the expected error message as second parameter.
*
* ``` php
* <?php
* $I->seeFormErrorMessage('username');
* $I->seeFormErrorMessage('username', 'Username is empty');
* ```
* @param string $field
* @param string|null $message
*/
public function seeFormErrorMessage(string $field, $message = null)
{
$formCollector = $this->grabCollector('form', __FUNCTION__);

if (!$forms = $formCollector->getData()->getValue('forms')['forms']) {
$this->fail('There are no forms on the current page.');
}

$fields = [];
$errors = [];

foreach ($forms as $form) {
foreach ($form['children'] as $child) {
$fieldName = $child['name'];
$fields[] = $fieldName;

if (!array_key_exists('errors', $child)) {
continue;
}
foreach ($child['errors'] as $error) {
$errors[$fieldName] = $error['message'];
}
}
}

if (array_search($field, $fields) === false) {
$this->fail("the field '$field' does not exist in the form.");
}

if (!array_key_exists($field, $errors)) {
$this->fail("No form error message for field '$field'.");
}

if (!$message) {
return;
}

$this->assertStringContainsString(
$message,
$errors[$field],
sprintf(
"There is an error message for the field '%s', but it does not match the expected message.",
$field
)
);
}

/**
* Checks that the user's password would not benefit from rehashing.
* If the user is not provided it is taken from the current session.
Expand Down

0 comments on commit 0db0214

Please sign in to comment.