當我運行我的rspec測試時,很多因我mongodb數據庫中陳舊的數據而失敗。 AFAIK用乾淨的數據庫進行測試要好得多。在Rails 3上用Rspec和MongoID清理或重置測試數據庫
用mysql,我可以運行rake db:test:prepare
來清理數據庫。在每次測試之前,如何清理nd /或重新生成數據庫?
當我運行我的rspec測試時,很多因我mongodb數據庫中陳舊的數據而失敗。 AFAIK用乾淨的數據庫進行測試要好得多。在Rails 3上用Rspec和MongoID清理或重置測試數據庫
用mysql,我可以運行rake db:test:prepare
來清理數據庫。在每次測試之前,如何清理nd /或重新生成數據庫?
如果您使用的是MongoID,您可以使用Database Cleaner和截斷策略。例如:
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
恕我直言,這是比安裝一個寶石用於清理你的數據庫的特定目的的好得多的解決方案.... 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 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}
對不起。我沒有看到你的回答,就評論上面的回覆。 Upvoted爲'Mongoid :: Sessions.default'就像'Mongoid.default_session'一樣正常工作。 – Alessandro
@Alessandro - 謝謝,我不知道關於Mongoid.default_session – declan
加入的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 3 **,你會需要類似於: 'Mongoid.default_session.collections.select {| c | c.name!〜/ system /} .each(&:drop)' – Alessandro
這完全是個挑剔的問題,實際上可能根本不重要,但是你的解決方案有點低效。您正在迭代所有集合,然後遍歷每個集合中的子集。 這只是迭代收集一次: 'Mongoid.default_session.collections.each {| coll | coll.drop除非/^system/.match(coll.name)}' –