ruby-on-railsrspecmongoid

Configuring RSpec with new Rails/MongoID application


I'm starting a new app and notice some missing documentation from the last time I built a MongoID app from scratch. Namely they used to suggest on a page that no longer exists (http://mongoid.org/docs/integration/) to include some code to drop MongoID's collections (after tests).

It's not mentioned on site anymore...is this (**** below) no longer considered necessary or good practice?!?

#spec/spec_helper.rb:
...
RSpec.configure do |config|

  config.mock_with :rspec

  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  #config.fixture_path = "#{::Rails.root}/spec/fixtures"

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  #config.use_transactional_fixtures = true

  # Below from <http://mongoid.org/docs/integration/>  ****
  config.after :suite do
    Mongoid.master.collections.select do |collection|
      collection.name !~ /system/
    end.each(&:drop)
  end
end

Solution

  • Modify the file spec/spec_helper.rb to add this:

    RSpec.configure do |config|
      # Other things
    
      # Clean up the database
      require 'database_cleaner'
      config.before(:suite) do
        DatabaseCleaner.strategy = :truncation
        DatabaseCleaner.orm = "mongoid"
      end
    
      config.before(:each) do
        DatabaseCleaner.clean
      end
    end