Automatically Run Your Specs Before Committing in Git

Written by

Ever accidentally commit some code, push it, and then find out that there were failing specs? Ouch, me too. I’ve got some good news, though: Git has the ability to run a script before it allows code to be committed through Git Hooks. With this ability we can run our specs before the code is committed and only the commit if the specs pass.

In every git project you can edit the pre-commit-hook by editing .git/hooks/pre-commit.

Here’s my pre-commit hook:

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/sh

branch=`git rev-parse --abbrev-ref HEAD`

if [ $branch == 'master' ]; then
  exit_code=$(bundle exec rspec --fail-fast --out /dev/null --format progress > /dev/null 2>/dev/null )$?
  if [ $exit_code -gt 0 ]
    then echo "Did not Commit because of failing tests"
  fi
  exit $exit_code
fi

exit 0

This fairly small script checks the current branch, saves it to a variable and the only runs the specs if we’re on master. If the specs fail then a message is output, otherwise the code is committed.

One last thing, you can skip running the specs and commit like this: git commit --no-verify


git

Comments or Questions? Contact Nick @nixterrimus on twitter.

Nick is a software engineer, geek, web enthusaist, open source contributor, home automation tinkerer, ocean admirer and all around general optimist living in San Francisco. Want to get in touch about professional matters? Nick Rowe is also available on LinkedIn.