Continuous Testing with RSpec and Guard - Better together

10 mins

-

"2022-04-18T13:05:27.220Z"

Introduction

I really enjoy the TDD workflow of creating tests before the implementation, but it's a drag to run tests manually. We can use Guard to watch and rerun our tests and application code as we make changes to them.

Setup

Add the following to your Gemfile:

group :development, :test do
gem 'spring'
gem 'spring-commands-rspec'
gem 'guard-rspec', require: false
# other development and test gems follow
end

and install the gems using bundler as normal:

bundle install

Initialize Guard:

bundle exec guard init

This will create Guardfile which is heavily commented:

# A sample Guardfile
# More info at https://github.com/guard/guard#readme
guard :rspec, cmd: "bundle exec rspec" do
require "guard/rspec/dsl"
dsl = Guard::RSpec::Dsl.new(self)
# Feel free to open issues for suggestions and improvements
# RSpec files
rspec = dsl.rspec
watch(rspec.spec_helper) { rspec.spec_dir }
watch(rspec.spec_support) { rspec.spec_dir }
watch(rspec.spec_files)
# Ruby files
...

To use Guard and RSpec with Spring install the Spring binstubs using:

bundle exec spring binstub rspec

Then change your Guardfile to use this:

guard :rspec, cmd: 'bin/rspec' do
require "guard/rspec/dsl"
dsl = Guard::RSpec::Dsl.new(self)
...

Start up Guard:

bundle exec guard

Now when you edit a spec it should be run automatically.