【发布时间】:2011-09-28 20:14:20
【问题描述】:
当我运行我的 rspec 测试时,由于我的 mongodb 数据库中的数据过时,许多测试都失败了。 AFAIK 使用干净的数据库进行测试要好得多。
使用 mysql,我可以运行 rake db:test:prepare 来清理数据库。如何在每次测试之前清理和/或重新植入数据库?
【问题讨论】:
标签: ruby-on-rails-3 rspec mongoid
当我运行我的 rspec 测试时,由于我的 mongodb 数据库中的数据过时,许多测试都失败了。 AFAIK 使用干净的数据库进行测试要好得多。
使用 mysql,我可以运行 rake db:test:prepare 来清理数据库。如何在每次测试之前清理和/或重新植入数据库?
【问题讨论】:
标签: ruby-on-rails-3 rspec mongoid
如果您使用多个 MongoDB 客户端,或者您不使用默认客户端,例如,您可以在 mongoid.yml 中创建一个新客户端,例如:'actions'。
您需要指定连接名称。 例如对于“动作”客户端使用:
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner[:mongoid, { connection: :actions }].start
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner[:mongoid, { connection: :actions }].clean
DatabaseCleaner.clean
end
【讨论】:
添加到 gemfile:
gem 'database_cleaner', :github => 'bmabey/database_cleaner'
运行bundle install
将此添加到您的 spec_helper:
config.before(:suite) do
DatabaseCleaner[:mongoid].strategy = :truncation
DatabaseCleaner[:mongoid].clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
全部功劳归于: http://blog.codelette.com/2013/07/07/make-rspec-clean-up-mongoid-records/
【讨论】:
【讨论】:
Mongoid.purge! 适用于我的 4.0.2,我认为它比使用 DatabaseCleaner 更好。
其他答案都不适用于 Mongoid 3.0。我用@Batkins 的答案修改了这样
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
或者,如果您想清空集合但又不想删除它(也许您有索引或其他东西),请执行此操作
Mongoid::Sessions.default.collections.select {|c| c.name !~ /system/}.each {|c| c.find.remove_all}
【讨论】:
Mongoid::Sessions.default 和Mongoid.default_session 一样好。
恕我直言,这是一个比为清理数据库的特定目的安装 gem 更好的解决方案.... 3 行进入您的 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
信用:A user named Alex posted this as a solution for a similar question.
【讨论】:
Mongoid.default_session.collections.select {|c| c.name !~ /system/ }.each(&:drop)
Mongoid.default_session.collections.each { |coll| coll.drop unless /^system/.match(coll.name) }
如果您使用的是 MongoID,您可以将 Database Cleaner 与 Truncation 策略一起使用。例如:
RSpec.configure do |config|
config.use_transactional_fixtures = false
config.before :each do
DatabaseCleaner.strategy = :truncation
DatabaseCleaner.start
end
config.after do
DatabaseCleaner.clean
end
end
【讨论】: