Alan W. Smith Alan W. Smith - 6 months ago 15
Ruby Question

Automatically run RSPec when plain-old Ruby (not Rails) files change

I am writing a Ruby script designed to run from the command line. The script has a corresponding RSpec file that verifies its functionality. The folder structure is:

./main_script.rb
./spec/main_script_spec.rb


Running
rspec spec
in the top level directory works as expected. Test results from the
./spec/main_script_spec.rb
file are shown. I'd like to avoid running this manually every time I change either the main script file or the spec file. All my search results turn up things like guard which (as far as I can tell) are all designed for Rails apps.

How do I setup RSpec to watch for script or spec changes and run automatically with non-Rails Ruby code?

Answer

Like David said, Guard can be used to watch a wide variety of files and perform actions when those files are modified. It does not have to be used with a Rails app. I have set up something similar in the past using guard. Here is what I did:

Place the following in your Gemfile:

source 'https://rubygems.org'

gem 'guard'
gem 'guard-shell'
gem 'rspec'
gem 'rb-fsevent', '~> 0.9'

Then run:

$ bundle install

Create a Guardfile in your home directory with:

$ guard init

In the Guardfile, comment out the examples and add this:

guard :shell do
  watch(%r{^*\.rb}) { `bundle exec rspec spec/` }
end

This tells guard to watch for modifications to any ruby files in the directory and execute the command bundle exec rspec spec/ when they change (the backticks are used to execute the command in the shell).

Then open up a new terminal window in your current directory and start a guard server to start watching the files:

$ bundle exec guard

Now your Rspec test suite should automatically run when you modify ruby files in the directory.