Git Pre-commit Hook to Auto Run PHPUnit

November 20 2015, 10:53am

Never push up broken tests again. Using a pre-commit hook for git, when you type in git commit git will automatically run your unit tests to make sure nothing is broken with your recent changes.

Create a file called pre-commit in your project root at ./.git/hooks/ and put the following code inside it:

#!/usr/bin/php
<?php
printf("%sGit pre-commit hook %1\$s", PHP_EOL);
$projectName = basename(getcwd());
exec('vendor/bin/phpunit', $output, $returnCode);
if ($returnCode !== 0) {
    $minimalTestSummary = array_pop($output);
    printf("Test suite for %s failed: ", $projectName);
    printf("( %s ) %s%2\$s", $minimalTestSummary, PHP_EOL);
    return false;
}
printf("All tests for %s passed.%s%2\$s", $projectName, PHP_EOL);
return true;


The above is based on this gist but updated to use the copy of phpunit from your project's composer.