Skip to content

Instantly share code, notes, and snippets.

@lcube45
Created October 10, 2016 15:04
Show Gist options
  • Save lcube45/c024e1423b3639258d01080c13462788 to your computer and use it in GitHub Desktop.
Save lcube45/c024e1423b3639258d01080c13462788 to your computer and use it in GitHub Desktop.
Behat : add screenshot on error
<?php
class FeatureContext extends MinkContext {
/**
* Take screenshot when step fails. Works only with Selenium2Driver.
* Screenshot is saved at [Date]/[Feature]/[Scenario]/[Step].jpg
*
* @AfterStep @javascript
*/
public function takeScreenshotAfterFailedStep(Behat\Behat\Event\StepEvent $event) {
if ($event->getResult() === Behat\Behat\Event\StepEvent::FAILED) {
$driver = $this->getSession()->getDriver();
if ($driver instanceof Behat\Mink\Driver\Selenium2Driver) {
$step = $event->getStep();
$path = array(
'date' => date("Ymd-Hi"),
'feature' => $step->getParent()->getFeature()->getTitle(),
'scenario' => $step->getParent()->getTitle(),
'step' => $step->getType() . ' ' . $step->getText()
);
$path = preg_replace('/[^\-\.\w]/', '_', $path);
$filename = '/tmp/behat/' . implode('/', $path) . '.jpg';
// Create directories if needed
if (!@is_dir(dirname($filename))) {
@mkdir(dirname($filename), 0775, TRUE);
}
file_put_contents($filename, $driver->getScreenshot());
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment