I added a rails application_cleaner gem to the database to clear my database between specifications. Here is my current configuration for database_cleaner located in spec/spec_helper.rb :
config.before(:suite) do DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with(:truncation) DatabaseCleaner.start DatabaseCleaner.clean end config.before(:each) do DatabaseCleaner.clean end config.after(:each) do DatabaseCleaner.clean end config.after(:suite) do DatabaseCleaner.clean end
Now this configuration works fine until all recently launched specifications are skipped or not executed.
However, in case of an error (rspec does not give you a nice little E , such as minitest, it throws such a thing:
09:17:32 - INFO - Running: spec /usr/local/rvm/rubies/ruby-1.9.3-p392/lib/ruby/gems/1.9.1/gems/activerecord-4.0.1/lib/active_record/validations.rb:57:in `save!': Validation failed: Email has already been taken (ActiveRecord::RecordInvalid)
), the database is not cleared! Residual data from the specification before the error remains in the database. I assume that this is because database_cleaner does not consider the erroneous specification complete and therefore does not clear the database.
Now it does no harm until you run your specs again. The residual data then leads to an error similar to this:
09:17:32 - INFO - Running: spec /usr/local/rvm/rubies/ruby-1.9.3-p392/lib/ruby/gems/1.9.1/gems/activerecord-4.0.1/lib/active_record/validations.rb:57:in `save!': Validation failed: Email has already been taken (ActiveRecord::RecordInvalid)
The workaround for this error is quite simple; running rails_env=test rake db:reset or starting the database shell and releasing the corresponding tables using sql statements will clear this data and allow you to run the specifications without crashing.
However, this is annoying. One wrong character in any of my specifications (something to make it wrong, not crashing) makes the whole testing process wedge, almost like an automatic weapon firing mechanism!
What are your suggestions regarding database_cleaner? Do you have any example configurations that allow you to clean up the database even in the event of an error test?
I use guard to run my rspecs, which are further enhanced with factory -girl:
Gemfile:
source 'https://rubygems.org' group :development do gem 'capistrano' gem 'rb-fsevent' gem 'debugger' end group :development, :test do gem 'rspec-rails', '~> 2.14.0' gem 'sqlite3' gem 'guard-rspec' gem 'guard-livereload', require: false gem 'guard-shell' gem 'webrick', '~> 1.3.1' end group :test do gem 'factory_girl_rails' gem 'capybara', '~> 2.2.0' gem 'selenium-webdriver'
specifications / spec_helper:
# This file is copied to spec/ when you run 'rails generate rspec:install' ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' require 'capybara/rspec'