Clean out, or reset test-database with Rspec and MongoID on Rails 3

berkes picture berkes · Jul 5, 2011 · Viewed 15.4k times · Source

When I run my rspec tests, many fail due to stale data in my mongodb database. AFAIK it is far better to test with a clean database.

With mysql, I could run rake db:test:prepare to clean up the database. How can I clean nd/or re-seed the database before each test?

Answer

declan picture declan · Jul 31, 2012

Neither of the other answers work for me with Mongoid 3.0. I used @Batkins answer modified like so

RSpec.configure do |config|

  # Clean/Reset Mongoid DB prior to running each test.
  config.before(:each) do
    Mongoid::Sessions.default.collections.select {|c| c.name !~ /system/ }.each(&:drop)
  end
end

Alternatively, if you want to empty the collection but don't want to drop it (maybe you have indexes or something), do this

Mongoid::Sessions.default.collections.select {|c| c.name !~ /system/}.each {|c| c.find.remove_all}