Testing 1 2 3
Column
In Behat, anything that doesn’t throw an exception is treated as a success. Every custom step definition presents the developer with the responsibility to check for exceptions and the opportunity to increase the value of scenario automation by providing meaningful feedback about failure.
We’ll explore this opportunity in the custom step definitions in the following scenario for a site whose main source of income results from presenting a discounted sale product on the front page:
Scenario: Daily Deal discount
Given I am on the homepage
When I click the Daily Deal "Buy now!" link
Then I should see the product title
And the sale price should reflect the discount advertised on the homepage
The product and discount change daily, so instead of matching literal text, the first custom step will use a css selector to find the discount amount and product title.
To start implementing, run the scenario to generate stubs for the custom steps. Note: --append-snippets can be used to write the output directly to the FeatureContext.php file.
It wouldn’t be uncommon to find the first custom step implemented with something like:
/**
* @When /^I click the Daily Deal "([^"]*)" link$/
*/
public function iClickTheDailyDealLink($linkText) {
$page = $this->getSession()->getPage();
// Limit to the Daily deal block
$el = $page->find('css','#daily');
// Find the title for use in the next step
$this->product = $el->find('css','h2')->getText();
// Find the discount amount for use in the next step
$this->discount = $el->find('css','span#dd-discount')->getText();
// Go to the product page
$link = $el->findLink($linkText);
if (empty($link)) {
throw new Exception('Link not found');
}
$link->click();
}
There are many ways to improve this step definition, but with respect to exceptions, the first and perhaps most important thing is: