This is how to set up RSpec and Guard in your Rails application for getting started in writing automated tests.

In your Gemfile, add the following:


group :development, :test do
gem 'rspec-rails', '2.14.1'
gem 'spring-commands-rspec'
gem 'guard-rspec'
gem 'rb-fsevent'
gem 'fabrication', '2.11.3'
gem 'sqlite3'
end

group :test do
gem 'capybara', '2.4.1'
gem 'faker'
gem 'shoulda-matchers'
gem 'selenium-webdriver', '2.43'
gem 'capybara-webkit'
gem 'database_cleaner'
end

Then,  run `bundle install` to install all your new gems.

Once these gems are successfully installed, run the following command: `guard init`

The above command will create the file “Guardfile” in the root directory of your application. However, it’s an example Guardfile so we need to change it:


guard :rspec, cmd: 'spring rspec' do
watch(%r{^spec/.+_spec\.rb$})
watch(%r{^lib/(.+)\.rb$}) { |m| "spec/lib/#{m[1]}_spec.rb" }
watch('spec/spec_helper.rb') { "spec" }

# Rails example
watch(%r{^app/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
watch(%r{^app/(.*)(\.erb|\.haml|\.slim)$}) { |m| "spec/#{m[1]}#{m[2]}_spec.rb" }
watch(%r{^app/controllers/(.+)_(controller)\.rb$}) { |m| ["spec/routing/#{m[1]}_routing_spec.rb", "spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb",            "spec/acceptance/#{m[1]}_spec.rb"] }
watch(%r{^spec/support/(.+)\.rb$}) { "spec" }
watch('config/routes.rb') { "spec/routing" }
watch('app/controllers/application_controller.rb') { "spec/controllers" }
watch('spec/rails_helper.rb') { "spec" }

# Capybara features specs
watch(%r{^app/views/(.+)/.*\.(erb|haml|slim)$}) { |m| "spec/features/#{m[1]}_spec.rb" }

# Turnip features and steps
watch(%r{^spec/acceptance/(.+)\.feature$})
watch(%r{^spec/acceptance/steps/(.+)_steps\.rb$}) { |m| Dir[File.join("**/#{m[1]}.feature")][0] || 'spec/acceptance' }
end

 

Now, when you run `bundle exec guard`, your specs will automatically run every time you edit your code.

When I’m working on a project, I generally like to keep a terminal window at the top of my computer screen so I can keep watch to make sure everything is passing correctly:

A picture of Guard