How to configure Cucumber and RSpec to work with Mongoid 3.0 | Adventures In Coding

How to configure Cucumber and RSpec to work with Mongoid 3.0

  • Kevin Faustino

With the upcoming release of Mongoid 3.0, I have decided to update a previous post about getting Mongoid to play nice with RSpec and Cucumber.

RSpec and Cucumber by default are setup to work with relational databases using ActiveRecord. To get them to work with Mongoid, we had previously run: {|c| !~ /system/ }.each(&:drop) in before hooks. The previous line will no longer work in Mongoid 3.0, as we now access databases via sessions. As of Mongoid version 2.0.2, the method Mongoid.purge! was added to easily drop all collections and indexes from your MongoDB database. This is what you should use moving forward.


The following example spec_helper.rb file is the bare minimum you will need to get Mongoid running with RSpec:

# spec_helper.rb

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

RSpec.configure do |config|
  config.mock_with :rspec

  config.before :each do


Cucumber allows defining hooks in any file under the features/support directory. To setup Cucumber, create a file features/support/hooks.rb that will drop your MongoDB collections before each scenario:

# features/support/hooks.rb

Before do |scenario|


blog comments powered by Disqus