How To Fix RSpec Error: "Validation failed: [Object] has already been taken"
I was programming a Ruby on Rails app today when I came across a strange bug. After installing the VCR Gem my RSpec tests began failing after the first one was run. The result was that every I updated my spec, I was forced to run the standard rake db:test:prepare
command to get things working.
I had no idea the cause of this since typically RSpec just works (it automatically deletes your test database after every run). The only thing that changed was the installation of the VCR gem, which makes me think it was the cause. Anyways, if you’re looking for the solution like I was, Natasha Murashev filled me in on the solution.
You’ll first need to install the database cleaner gem. You can add the following line to the the group :test area of your Gemfile:
gem 'database_cleaner', '0.9.1'
Next up, add the following line to the top of your spec_helper.rb file:
DatabaseCleaner.strategy = :truncation
Finally, assuming you are using Guard and Spork, add the following line within the Spork.each_run
block:
DatabaseCleaner.clean
If it’s still not working, you may have to include the gem within the spec_helper file by adding require 'database_cleaner'
to the top. That’s it!