← all posts

Running only updated rspec files

As your Rails app gets larger, it becomes difficult and time consuming to run the full test suite locally when making changes.

Of course, your CI/Build process should always run all specs (and pass!) before merging, but for local development it’s often convenient to quickly test just those rspec files that have been updated in your feature branch.

I use a bash helper function that will –

  1. Diff my current branch against master (or some other desired branch)
  2. Find out what spec files have been changed on my branch
  3. Eliminate any non-runnable files like spec_helper.rb
  4. Run those files

Writing it

Add the following to your .bash_profile

                
function run_changed_specs {
  arg=$1
  branch=${arg:-master}

  files=$(git diff $branch..HEAD --name-only | grep spec | grep -v spec_helper.rb)

  echo "==="
  echo "Running files changed since $branch:"
  echo $files
  echo ""

  rspec $(echo $files | tr '\n' ' ')
}
                
              

The above function eliminates spec_helper.rb since it’s not a runnable file.

You may want to add other grep pipes for things you’d like to eliminate in your own app, like spec/support if you have support files or spec/factories if you use FactoryBot.

Running it

Now open a new terminal window (or source your .bash_profile again) and you can just run the function directly!

                
> run_changed_specs
===
Running files changed since master:
spec/features/admin/creating_a_user.rb spec/models/user_spec.rb spec/services/users/create_user_service.rb

Randomized with seed 46260
..................

Finished in 9.46 seconds (files took 1.39 seconds to load)
18 examples, 0 failures

Randomized with seed 46260
                
              

If you want to diff against some other branch besides master, you can specify that as an argument

                
> run_changed_specs my-release-branch