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?
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}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With