Skip to content

Instantly share code, notes, and snippets.

@tushar-dadlani
Last active December 26, 2015 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tushar-dadlani/7150802 to your computer and use it in GitHub Desktop.
Save tushar-dadlani/7150802 to your computer and use it in GitHub Desktop.
pre-commit script for whiteboard. This script checks for syntax errors in models and controllers. This also runs the spec_no_rails test cases and doesn't allow a commit to happen if a test case is failing.
#!/bin/bash
# Derived from https://github.com/depy/my-git-hooks/blob/master/run-rspec-test-pre-commit
# Github username of original source: depy
# Author: Tushar Dadlani
# Instructions to install
# Copy this file to YOUR_RAILS_ROOT/.git/hooks/pre-commit.sh
# mv pre-commit.sh pre-commit
# chmod +x pre-commit
MACHINE=`uname`
# Colors for Linux and OS X
if [ $MACHINE = "Darwin" ]; then
{
GREEN='\x1B[0;32m'
RED='\x1B[0;31m'
ENDCOLOR='\x1B[0m'
}
elif [ $MACHINE = "Linux" ]; then
{
GREEN='\e[0;32m'
RED='\e[0;31m'
ENDCOLOR='\e[0m'
}
fi
# Stash unstaged changes before running tests
git stash -q --keep-index
# Check for syntax errors in all models and controllers (not in views so far).
for file in `find app -name "*.rb" -type f `
do
ruby -c $file 2>&1> /dev/null || {
echo "Fix syntax errors in your code and try again." && {
git stash pop -q
exit 1
}
}
done
# Run tests
RUN_TESTS_CMD='bundle exec rspec spec_no_rails'
read NUM_FAILS NUM_PASS <<< `${RUN_TESTS_CMD} --format=progress | grep "example"| grep "fail"| awk {'print $3,"\t", ($1 - $3) '} 2> /dev/null`
# Unstash
git stash pop -q
if [ $NUM_FAILS -ne 0 ]
then
printf "${RED}Cannot commit! \n${NUM_FAILS} tests failed.\n" || exit 1
printf "${GREEN}${NUM_PASS} tests passed.\n" || exit 1
printf "${ENDCOLOR}Run 'bundle exec rspec spec_no_rails' from your Rails root for more details.\n"
exit 1
else
printf "${GREEN}${NUM_PASS} tests passed in total.\n"
printf "You didn't break anything. Congrats!\n${ENDCOLOR}"
exit 0
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment