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 {
  }.to change(User, :count).by(1)

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

config.before(:each) do

config.after(:each) do

And whoila! Now my test passes in every run.