[Ruby] Run RSpec, Brakeman, Rubocop, RailsBest Practices on overcommit

1 minute read

Why did you decide to use overcommit?

  • I want to automatically execute tests and static analysis
  • Using git hooks, you can execute a specific script at the timing of commit, push, etc.
  • The contents of git hooks cannot be managed by git
  • You can manage and extend git hooks using overcommit

Assumption

  • Rspec (Test automation)
  • Brakeman (security check)
  • Rubocop (Ruby code analysis)
  • RailsBestPractices (Rails code analysis)

I have already introduced, and I will write it assuming that you can hit commands manually. If you have a tool that you are not using, ignore the settings for that part.

Introduction

Gemfile


group :development do
  gem'overcommit'
$ bundle install
$ overcommit --install # generate configuration file

.overcommit.yml


# Disable unnecessary checks
CommitMsg:
  ALL:
    enabled: false
PreCommit:
  AuthorEmail:
    enabled: false
  AuthorName:
    enabled: false
  BrokenSymlinks:
    enabled: false
  CaseConflicts:
    enabled: false
  MergeConflicts:
    enabled: false
# Required check settings
  RuboCop:
    enabled: true
  RailsBestPractices:
    enabled: true
PrePush:
  Brakeman:
    enabled: true
  RSpec:
    enabled: true
$ overcommit --sign # Reflect the setting change

In addition, Default setting is applied except for the items explicitly set in the configuration file.

Operation check

Below is an example of how to check the operation. Rubocop Embed Time.now in an appropriate controller and confirm that you cannot commit RailsBest Practices Set default_scope order(created_at: :desc) to an appropriate model and confirm that you cannot commit Brakeman Set http_basic_authenticate_with name:'ID', password:'password' to the appropriate controller and check that Push is not possible RSpec Write a test that doesn’t pass and make sure you can’t push

Where I got hooked

Although I passed RSpec manually, I couldn’t pass the pre-push check and the following message was displayed.

NameError:
  uninitialized constant Capybara::DSL

When hitting manually, bin/rspec is executed, but when pre-push, bundle exec rspec is executed, so the behavior seems to be slightly different. Solved by adding the following to spec_helper.rb.

spec/spec_helper.rb


RSpec.configure do |config|
  # Add the following 3 lines
  ENV['RAILS_ENV'] ||='test'
  require File.expand_path('../config/environment', __dir__)
  require'rspec/rails'

Reference