Skip to content

Instantly share code, notes, and snippets.

@stmllr
Forked from fbrnc/gist:4550079
Last active December 16, 2015 11:49
Show Gist options
  • Save stmllr/5430470 to your computer and use it in GitHub Desktop.
Save stmllr/5430470 to your computer and use it in GitHub Desktop.
Take screenshot after a step failed in Behat/Mink using Selenium WebDriver
<?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());
}
}
}
}
@bizmate
Copy link

bizmate commented Nov 20, 2013

Does not seem to work anymore. Adding the function to the FeatureContext didnt hook it up with an afterStep. Has anything changed recently? Is this still working for you?

@linusnorton
Copy link

@bizmate still works for me however the screenshots are saved as png not jpg.

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