Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a pre-commit git hook runs rspec tests and prevent a commit?

How can I add a pre-commit hook that will run my rspec tests and if any fail, will not complete the commit. I can get the tests to run but not prevent the commit on any failure of them

I have copied .git/hooks/pre-commit.sample to .git/hooks/pre-commit

I've added rspec spec near the bottom.

The tests run as part of the commit... but a failure doesn't stop the commit from completing.

$ git commit -m'test'
....................................................................................................F.............

Failures:

  1) Link Good url SHOULD be valid
     Failure/Error: expect(link.valid_get?).to be false #true

       expected false
            got true
     # ./spec/models/link_spec.rb:26:in `block (2 levels) in <top (required)>'

Finished in 32.78 seconds (files took 3.58 seconds to load)
114 examples, 1 failure

Failed examples:

rspec ./spec/models/link_spec.rb:24 # Link Good url SHOULD be valid
[79230846_hook_to_run_tests 6c09570] test
 1 file changed, 1 insertion(+)
 create mode 100644 x.x 

Maybe I need a different way to run the rspec tests that will raise the non-zero error I need ?

Currently it is placed at the bottom:

    ...
    echo
    echo "  git config hooks.allownonascii true"
    echo
    exit 1
fi

rspec spec

exec git diff-index --check --cached $against --

I'm doing all this in a branch (not master). Didn't know if that was relevant.

like image 610
Michael Durrant Avatar asked Sep 20 '14 21:09

Michael Durrant


2 Answers

I found that using

exec rspec spec

in

.git/hooks/pre-commit

gave me the desired functionality -
commit attempts trigger rspec test runs and the commit only complete if all rspec tests pass.

like image 56
Michael Durrant Avatar answered Oct 16 '22 14:10

Michael Durrant


If the pre-commit hook itself doing an exit zero, or is it just calling rspec?

It might be all you need to do is add exit $? after the rspec call.

like image 29
Andrew C Avatar answered Oct 16 '22 12:10

Andrew C