Setting up Spec for rails testing

By | 05/02/2017

I’m getting to grips with RSpec for testing and getting to grips with some of it’s functionality.  To play around with some of the features I’m building a side project of an employee database, nothing too fancy but just something that stores all the features of an employee, i.e. name, salary, email, location, phone number etc. Most of the data will be purely for testing so will come from the Faker gem.

I’m following a few guides but as per usual thought I’d keep my set up notes here for future reference… until I become a full fledged Rails developer and can do this with my eyes closed!

Setting up RSpec

add relevant gems to Gemfile

group :development, :test do
gem 'rspec-rails'
gem 'guard-rspec'

group :test do
gem 'database_cleaner'

Then run
$ rails g spec:install 
$ bundle exec guard init

This will install the Spec framework. Guard automates the running of your tests and with guard running ($ guard) your tests will run every time a change is made to a file and you save the file.
The database cleaner gem ensures the test database is clean after running tests so there are no conflicts.

In the spec/rails_helper.rb file you should have the following:
require 'spec_helper'
require 'rspec/rails'
require 'database_cleaner'

scroll down and add the following:
config.use_transactional_fixtures = false

config.before(:each) do |example|
  DatabaseCleaner.strategy = example.metadata[:js] ? :truncation : :transaction
#using truncation for js tests and transaction otherwise

config.before(:each) do

Finally add capybara to simulate user interaction test.
gem 'capybara'
run $bundle install 
and add 
require 'capybara/rspec' to the spec/rails_helper.rb file.

If using seed data add
gem 'factory_girl_rails' and run bundle install.

This will allow test data to be added data to your test database for testing in Spec.