Skip to content

Instantly share code, notes, and snippets.

@wouterj
Created January 12, 2015 14:16
Show Gist options
  • Select an option

  • Save wouterj/e9385f76f2e5cc11d951 to your computer and use it in GitHub Desktop.

Select an option

Save wouterj/e9385f76f2e5cc11d951 to your computer and use it in GitHub Desktop.
<?php
// BEFORE
// ...
class FeatureContext
{
public function assertFieldHasErrorMessage($message, $locator)
{
// find fieldset by locator for field
$field = $this->getSession()->getPage()->findField($locator);
if (!$field) {
// find fieldset by label (e.g. a radiobutton field)
$field = $this->findLabel($locator);
if (!$field) {
throw new Exception\ElementNotFoundException($this->getSession(), 'field', null, $locator);
}
$field = $field->getParent();
}
$fieldWrapper = $field->getParent();
$actual = $fieldWrapper->getText();
$regex = '/'.preg_quote($message, '/').'/ui';
if (!preg_match($regex, $actual)) {
throw new Exception\ElementTextException(sprintf('Field "%s" did not have the error message "%s".', $locator, $message), $this->getSession(), $fieldWrapper);
}
}
protected function findLabel($locator)
{
return $this->getSession()->getPage()->find(
'xpath',
"//label[contains(text(), '".$locator."')]"
);
}
}
<?php
// AFTER
// ...
class FeatureContext
{
public function assertFieldHasErrorMessage($message, $locator)
{
// how can I implement the same search as above for the $locator fieldset?
expect($this->currentPage->getElement($locator.' fieldset'))->toNotHaveErrorMessage($message);
}
}
@jakzal

jakzal commented Jan 12, 2015

Copy link
Copy Markdown
<?php
namespace Page;

use SensioLabs\Behat\PageObjectExtension\PageObject\Page;

class MyPage extends Page
{
    public function findFieldError($locator)
    {
       // find fieldset by locator for field
        $field = $this->findField($locator);

        if (!$field) {
            // find fieldset by label (e.g. a radiobutton field)
            $field = $this->findLabel($locator);

            if (!$field) {
                throw new Exception\ElementNotFoundException($this->getSession(), 'field', null, $locator);
            }

            $field = $field->getParent();
        }
        $fieldWrapper = $field->getParent();
        $actual  = $fieldWrapper->getText();

        return $actual;
    }

    protected function findLabel($locator)
    {
        return $this->find(
            'xpath',
            "//label[contains(text(), '".$locator."')]"
        );
    }
}
<?php

// ...
class FeatureContext
{
    public function assertFieldHasErrorMessage($message, $locator)
    {
        $foundMessage = $this->currentPage->findFieldError($locator.' fieldset');

        expect($foundMessage)->toBe($message);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment