It actually wasn’t that long ago that I stumbled upon git hooks and let me tell you – I was instantly hooked (he he). Git has triggers that can kick off custom scripts to run before an action. These are especially useful to help you remember to perform tasks at hand.

In example: previously I had to manually remember to run my tests before pushing it live, at least in the smaller projects where I didn’t have any active CI like Jenkins running. Most of the times, no problems. But sometimes it’s easy to forget to run those tests when you’re in a hurry. Enter git hooks!

There are a few triggers we can hook up to, the most widely used are pre-commit and pre-push. Remember that they will not continue with the operation if the status from the script you are running returns anything else than 0 as exit status.

So, to run your tests in Rails before a commit you only need to do this in the root of your project

nano .git/hooks/pre-commit

And in your pre-commit file:

#!/bin/sh
rake spec

In order for git to be able to run the bash script you need to change the file to an executable

chmod +x .git/hooks/pre-commit

All done! Now just try to commit and you will see that the tests are executed before anything actually get’s committed to the repo.