I am currently working on a pet project in Rails that uses Mongoid to connect as its Object-Document-Mapper (which is similar to what Active Record does for SQL databases).

I then ran into issue when I had an RSpec test case that verified that tested a method that called find_or_create_by. In other words, a record should be created if it did not exist, otherwise the existing record should be returned.

So my test case looked something like this:
it 'creates entry from auth hash' do
  auth_hash = {'info' => {'name' =>  'Samuel Vimes'} }
  expect {
    User.find_or_create_from_auth_hash(auth_hash)
  }.to change(User, :count).by(1)
end

This test was green the first time I ran it, but failed the second time. The reason was that the database was not being cleaned up in between test runs.

Database Cleaner by Ben Mabey to the rescue. I added this to the :test group of my Gemfile:
gem 'database_cleaner', :github => 'bmabey/database_cleaner'
And this to the configure block of my spec_helper:
# Cleanup the DB in between test runs
config.before(:suite) do
  DatabaseCleaner[:mongoid].strategy = :truncation
  DatabaseCleaner[:mongoid].clean_with(:truncation)
end

config.before(:each) do
  DatabaseCleaner.start
end

config.after(:each) do
  DatabaseCleaner.clean
end

And whoila! Now my test passes in every run.