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

Viewed 16046

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?

6 Answers

If you using with multiple MongoDB clients, or you don't work with the default client, for example, you create a new client in mongoid.yml like: 'actions'.

you need to specify the connection name. for example for 'actions' client use:

config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end

config.before(:each) do
  DatabaseCleaner[:mongoid, { connection: :actions }].start
  DatabaseCleaner.start
end

config.after(:each) do
  DatabaseCleaner[:mongoid, { connection: :actions }].clean
  DatabaseCleaner.clean
end
Related