Prab's Code Blog

Because talk is cheap, show me the code!

Configure DatabaseCleaner With Rspec for Mongoid 5 and Beyond

Database Cleaner is a nifty gem for streamlining tests. Configuring it is straightforward but it didn’t work for me out of the box for Mongoid 5.

Here’s my Gemfile segment for testing.

Gemfile
1
2
3
4
5
6
group :test do
  gem "factory_girl_rails"
  gem "rspec-rails", '~> 3.4'
  gem 'faker'
  gem 'database_cleaner', git: 'git://github.com/DatabaseCleaner/database_cleaner.git'
end

I added a require 'support/database_cleaner' in my spec_helper. And here’s my database_cleaner.rb.

spec/support/database_cleaner.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
RSpec.configure do |config|

  config.before(:suite) do
    DatabaseCleaner.strategy = :truncation
    DatabaseCleaner.clean
  end

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

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

end

When I ran my spec, I was greeted with an unexpected ugly error.

1
2
3
4
5
6
/home/prabhakar/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/bundler/gems/database_cleaner-f052d64d3be9/lib/database_cleaner/mongo2/truncation_mixin.rb:29:in `collections': undefined method `collections' for #<Mongo::Client:0x47021052998580 cluster=127.0.0.1:27017> (NoMethodError)
  from /home/prabhakar/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/bundler/gems/database_cleaner-f052d64d3be9/lib/database_cleaner/mongo2/truncation_mixin.rb:9:in `clean'
  from /home/prabhakar/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/bundler/gems/database_cleaner-f052d64d3be9/lib/database_cleaner/base.rb:92:in `clean'
  from /home/prabhakar/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/bundler/gems/database_cleaner-f052d64d3be9/lib/database_cleaner/configuration.rb:79:in `block in clean'
  from /home/prabhakar/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/bundler/gems/database_cleaner-f052d64d3be9/lib/database_cleaner/configuration.rb:79:in `each'
  from /home/prabhakar/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/bundler/gems/database_cleaner-f052d64d3be9/lib/database_cleaner/configuration.rb:79:in `clean'

After looking at the code in the gem, I finally found out what was wrong in it. I created a commit for fix and submitted a pull request to the maintainer. Looking at my commit and the relevant files truncation.rb and truncation_mixin.rb, you should be able to piece together the problem.

Meanwhile, if you are using Mongoid 5 and aren’t able to get it working you could simply point to my fork of database_cleaner by updating your Gemfile to have:

Gemfile
1
gem 'database_cleaner', git: 'git://github.com/prabhakar97/database_cleaner.git'

Comments