Skip to content

Commit

Permalink
MDL-76169 behat: Normalise exception message in should (not) steps
Browse files Browse the repository at this point in the history
These steps have accepted a NodeElement instance as an argument for some
time, but were trying to cast it to string when formulating exception
messages, making it harder to debug and, in the case of the 'should see'
step, not work at all.

This patch introduces a new function to produce a consistent naming for
them.
  • Loading branch information
andrewnicols committed Nov 3, 2022
1 parent 414a995 commit e53e25a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
16 changes: 16 additions & 0 deletions lib/behat/classes/behat_session_trait.php
Expand Up @@ -224,6 +224,22 @@ public function normalise_selector(string $selector, $locator, Element $containe
];
}

/**
* Get a description of the selector and locator to use in an exception message.
*
* @param string $selector The type of locator
* @param mixed $locator The locator text
* @return string
*/
protected function get_selector_description(string $selector, $locator): string {
if ($selector === 'NodeElement') {
$description = $locator->getText();
return "'{$description}' {$selector}";
}

return "'{$locator}' {$selector}";
}

/**
* Send key presses straight to the currently active element.
*
Expand Down
7 changes: 5 additions & 2 deletions lib/tests/behat/behat_general.php
Expand Up @@ -1209,7 +1209,8 @@ public function should_exist_in_the($element, $selectortype, $containerelement,
$containernode = $this->find($containerselectortype, $containerelement);

// Specific exception giving info about where can't we find the element.
$locatorexceptionmsg = "{$element} in the {$containerelement} {$containerselectortype}";
$containerdescription = $this->get_selector_description($containerselectortype, $containerelement);
$locatorexceptionmsg = "{$element} not found in the {$containerdescription}}";
$exception = new ElementNotFoundException($this->getSession(), $selectortype, null, $locatorexceptionmsg);

// Looks for the requested node inside the container node.
Expand Down Expand Up @@ -1243,8 +1244,10 @@ public function should_not_exist_in_the($element, $selectortype, $containereleme
}

// The element was found and should not have been. Throw an exception.
$elementdescription = $this->get_selector_description($selectortype, $element);
$containerdescription = $this->get_selector_description($containerselectortype, $containerelement);
throw new ExpectationException(
"The '{$element}' '{$selectortype}' exists in the '{$containerelement}' '{$containerselectortype}'",
"The {$elementdescription} exists in the {$containerdescription}",
$this->getSession()
);
}
Expand Down

0 comments on commit e53e25a

Please sign in to comment.