Here’s how I usually setup my test environment on Rails. I’m using mainly RSpec and Capybara, so nothing new under the sun, but this should provide a mindless copy and paste to get you (mainly me) started.
First of all, the gems used. This configuration is in part taken from the book “Testing with RSpec” by Aaron Summer:
Gemfile
123456789101112131415
group:development,:testdogem'rspec-rails'gem'factory_girl_rails'gem'rb-fsevent',require:falseifRUBY_PLATFORM=~/darwin/i# only on OSXgem'guard-rspec'endgroup:testdogem'shoulda-matchers'gem'faker'gem'capybara'gem'poltergeist'gem'database_cleaner'# DatabaseCleaner required to test user authentication protected routesgem'launchy'# Provides the awesome save_and_open_page method in your capybara specsend
A pretty basic setup, RSpec with shoulda matchers, FactoryGirl + Faker for cool mocks and Capybara with Poltergeist as webdriver.
You might want to install PhantomJS (used by Poltergeist). In Mac OSX you can just use brew:
1
brew install phantomjs
With that out of the way the next step is to setup RSpec
1
rails g rspec:install
I like to customize rspec with the dotted (or the documentation if I’m feeling verbose) and colored notation by adding a .rspec file.
As you can see I let the generator create the fixtures (using FactoryGirl) and the controller and routes specs. I create models and request spec manually, and I don’t care for view specs.
That’s about it for Rails, the next step is to do some adjustments to the spec_helper:
ENV["RAILS_ENV"]||='test'requireFile.expand_path("../../config/environment",__FILE__)require'rspec/rails'#require 'rspec/autorun' #removed to support Zeusrequire'capybara/poltergeist'Dir[Rails.root.join("spec/support/**/*.rb")].each{|f|requiref}ActiveRecord::Migration.check_pending!ifdefined?(ActiveRecord::Migration)RSpec.configuredo|config|config.includeFactoryGirl::Syntax::Methodsconfig.filter_run_excludingslow:trueconfig.fixture_path="#{::Rails.root}/spec/fixtures"Capybara.javascript_driver=:poltergeist# DatabaseCleaner required to test user authentication protected routesconfig.use_transactional_fixtures=falseconfig.before(:suite)doDatabaseCleaner.strategy=:truncationendconfig.before(:each)doDatabaseCleaner.startendconfig.after(:each)doDatabaseCleaner.cleanendconfig.infer_base_class_for_anonymous_controllers=falseconfig.order="random"end
This sets up DatabaseCleaner and the webdriver for Capybara. It also tells RSpec to skip tests marked as :slow.
Other goodies
Almost there, now it’s time to setup a couple of tools that makes testing less cumbersome.
First of all, let’s setup Guard.
1
guard init rspec
… and that’s about it.
Let’s finish off by configuring Zeus if needed (or wanted). That’s pretty straightforward, we just need to change the test environment command in the zeus.json generated by zeus init: