Skip to content

Instantly share code, notes, and snippets.

@romaricdrigon
Created August 30, 2013 09:57
Show Gist options
  • Select an option

  • Save romaricdrigon/6388262 to your computer and use it in GitHub Desktop.

Select an option

Save romaricdrigon/6388262 to your computer and use it in GitHub Desktop.
Screenshots on Behat failed steps
default:
context:
class: Acme\Behat\Context\MyContext
parameters:
screenshots_path: web/tmp # don't forget to create and make writable this directory!
<?php
namespace Acme\Behat\Context;
use Behat\Behat\Context\BehatContext;
use Behat\MinkExtension\Context\MinkContext;
use Behat\Behat\Event\StepEvent;
class MyContext extends BehatContext
{
/**
* @var array
*/
protected $parameters;
/*
Behat pass parameters as an array to context constructor
*/
public function __construct(array $parameters)
{
$this->parameters = $parameters;
}
/**
* Take a screenshot when a (any) step fails.
* Works only with Selenium.
* @AfterStep
*/
public function takeScreenshotOnFailure(StepEvent $event)
{
if ($event->getResult() == StepEvent::FAILED) {
$path = $this->parameters['screenshots_path'];
$imageData = $this->getMink()->getSession()->getDriver()->getScreenshot();
$scenarioName = str_replace(' ', '_', $event->getStep()->getParent()->getTitle());
$filename = sprintf('fail_%s_%s.png', time(), $scenarioName);
file_put_contents(rtrim($path, '/').'/'. $filename, $imageData);
}
}
/**
* @return MinkContext
* @throws \RuntimeException
*/
protected function getMink()
{
$mink = $this->getMainContext()->getSubcontext('mink');
if (!$mink instanceof MinkContext) {
throw new \RuntimeException(sprintf('Expected a "MinkContext", got a "%s".', is_object($mink) ? get_class($mink) : gettype($mink)));
}
return $mink;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment