Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 587
berkes Avatar asked Jul 05 '11 13:07

berkes


2 Answers

Neither of the other answers work for me with Mongoid 3.0. I used @Batkins answer modified like so

RSpec.configure do |config|

  # Clean/Reset Mongoid DB prior to running each test.
  config.before(:each) do
    Mongoid::Sessions.default.collections.select {|c| c.name !~ /system/ }.each(&:drop)
  end
end

Alternatively, if you want to empty the collection but don't want to drop it (maybe you have indexes or something), do this

Mongoid::Sessions.default.collections.select {|c| c.name !~ /system/}.each {|c| c.find.remove_all}
like image 195
declan Avatar answered Oct 16 '22 12:10

declan


IMHO, This is a much nicer solution than installing a gem for the specific purpose of cleaning out your database.... 3 lines to go in your spec_helper.rb:

RSpec.configure do |config|
  #Other config stuff goes here

  # Clean/Reset Mongoid DB prior to running the tests
  config.before :each do
    Mongoid.master.collections.select {|c| c.name !~ /system/ }.each(&:drop)
  end
end

Credit: A user named Alex posted this as a solution for a similar question.

like image 18
Batkins Avatar answered Oct 16 '22 12:10

Batkins