Last active
April 18, 2018 18:48
-
-
Save megclaypool/be18201422fb7c0fef2ef6bbd7c7f8f5 to your computer and use it in GitHub Desktop.
Add this definition to your FeatureContext.php to take a screenshot of failed steps for your Behat/Selenium2 tests. It creates a directory called "screenshots" in your project directory (if one doesn't already exist) and within it places screenshots whose filenames consist of the date and time as well as the name of the failed step.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @AfterStep | |
*/ | |
public function takeScreenShotAfterFailedStep(afterStepScope $scope) | |
{ | |
if (99 === $scope->getTestResult()->getResultCode()) { | |
$driver = $this->getSession()->getDriver(); | |
$filePath = getcwd() . DIRECTORY_SEPARATOR . 'screenshots'; | |
if (!file_exists($filePath)) { | |
mkdir($filePath); | |
} | |
$stepText = $scope->getStep()->getText(); | |
$fileTitle = date('Y-m-d--H:i:s') . '--' . preg_replace("#[^a-zA-Z0-9\._-]#", '', $stepText); | |
$fileName = $filePath . DIRECTORY_SEPARATOR . $fileTitle . '.png'; | |
$screenshot = $this->getSession()->getDriver()->getScreenshot(); | |
file_put_contents($fileName, $screenshot); | |
print "Screenshot for '{$stepText}' placed in {$fileName}\n"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I worked out how to do this because my tests were working in Chrome and failing in PhantomJS. By looking at the screenshots, I realized that PhantomJS defaults to a very narrow window, which meant that it was testing the mobile site rather than the desktop site (and thus the menus I was testing weren't the same). You can resize your test browser window using this step definition: https://gist.github.com/megclaypool/42dc283beccc8085a15f6e9c106d74f1