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.

  • Digital Ocean git bare repo
  • heroku: How to swich apps from another environment
  • Share code/configurations/conventions/gems between Rails apps
  • env: node\r: No such file or directory with browserify-rails
  • Heroku thinks app is in same folder
  • Hartl's Ruby on Rails / Hello_App / Heroku Error H10
  • Does grit have to be on the same server as the repositories?
  • How to work with different versions of rails project at once?
  • 2 Solutions collect form web for “How can a pre-commit git hook runs rspec tests and prevent a commit?”

    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.

    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.

    Git Baby is a git and github fan, let's start git clone.