Useful aliases to run rubocop and specs you changed in your branch + a github trick

Tired of checking your PR for which files to run against?

Rob Faldo
2 min readMar 10, 2021

Run all specs that were changed by your branch:

git diff --diff-filter=d --name-only master... | grep _spec | xargs -n1 bundle exec rspec# Broken down # Get all files that are different on this branch compared to master (excluding ones that have been deleted - this is what --diff-filter=d ensures). 
git diff --diff-filter=d --name-only master...
# Of those, show files that are specs (could change this to include features etc...)
| grep _spec
# For each file name, run `bundle exec rspec FILENAME`
| xargs -n1 bundle exec rspec

Run rubocop on all modified files (before committing)

git ls-files -m | xargs ls -1 2>/dev/null | grep '\.rb$' | xargs bundle exec rubocop

Read this article for a breakdown of above.

Run rubocop on all files that were changed by your branch excluding deleted files (after committing):

git diff --diff-filter=d --name-only master... | xargs bundle exec rubocop

Autofixing rubocop errors

Remember that you can ask rubocop to automatically fix your errors by adding -a to the end of rubocop command (e.g. `git diff — name-only master… | xargs rubocop -a`)

Skip set-upstream when you first push a branch to remote

You’ll no doubts be familiar with this message

git push — set-upstream origin my-branch-name

You can use the below gpush alias to do it for you automatically:

# First time pushing a branch to remote 
alias gpush="function gpush() {
git push --set-upstream origin $(git symbolic-ref --short HEAD) || git push
}"

Putting them in an alias (bash)

# open your bashrc file in your editor of choice (or vim)
atom ~/.bashrc
####### Add aliases ######## Run all the specs that have been changed by your branch (excluding deleted files)
alias changed_specs="git diff --diff-filter=d --name-only master... | grep _spec | xargs -n1 bundle exec rspec"
# Run rubocop on all the files my branch has changed (excluding deleted files)
alias run_rubocop="git diff --diff-filter=d --name-only master... | xargs bundle exec rubocop"
# Run rubocop on changes before committing
alias run_rubocop_pre="git ls-files -m | xargs ls -1 2>/dev/null | grep '\.rb$' | xargs bundle exec rubocop"
# First time pushing a branch to remote
alias gpush="function gpush() {
git push --set-upstream origin $(git symbolic-ref --short HEAD) || git push
}"
################################ source your bashrc file
source ~/.bashrc

--

--