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

  • How to make git mark a deleted and a new file as a file move?
  • How can I push to a git bundle
  • How do I modify cygwin's PS1 for git bash completion?
  • Long-term usage of branches with “git worktree”
  • How to keep two repositories synced, in which one repository is child of the other?
  • Android studio git using private key
  • 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.

  • “git checkout <commit id>” is changing branch to “no branch”
  • Git: Turn current master into branch and keep uncommitted changes
  • A way to revert a whole branch in a single commit
  • Using Git on Windows, behind an HTTP proxy, without storing proxy password on disk
  • How to find local git branches that have been deleted from master
  • git - How to pull a branch from a specific branch
  • 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.