2011-07-05 60 views
14

當我運行我的rspec測試時,很多因我mongodb數據庫中陳舊的數據而失敗。 AFAIK用乾淨的數據庫進行測試要好得多。在Rails 3上用Rspec和MongoID清理或重置測試數據庫

用mysql,我可以運行rake db:test:prepare來清理數據庫。在每次測試之前,如何清理nd /或重新生成數據庫?

回答

16

如果您使用的是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 
18

恕我直言,這是比安裝一個寶石用於清理你的數據庫的特定目的的好得多的解決方案.... 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.

+9

如果您使用** Mongoid 3 **,你會需要類似於: 'Mongoid.default_session.collections.select {| c | c.name!〜/ system /} .each(&:drop)' – Alessandro

+7

這完全是個挑剔的問題,實際上可能根本不重要,但是你的解決方案有點低效。您正在迭代所有集合,然後遍歷每個集合中的子集。 這只是迭代收集一次: 'Mongoid.default_session.collections.each {| coll | coll.drop除非/^system/.match(coll.name)}' –

30

其他答案對我來說都不適用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} 
+1

對不起。我沒有看到你的回答,就評論上面的回覆。 Upvoted爲'Mongoid :: Sessions.default'就像'Mongoid.default_session'一樣正常工作。 – Alessandro

+0

@Alessandro - 謝謝,我不知道關於Mongoid.default_session – declan

7

在Mongoid V2.0.2

before(:each) do 
    Mongoid.purge! 
end 

Rdoc: Mongoid.purge!

+0

當我嘗試選擇的答案時,沒有工作,仍然有一些記錄是以某種方式創建的,這對我有幫助。由於某種原因,測試的速度也明顯加快。 – randomor

+0

我想你想要Mongoid :: Config.purge! – bonhoffer

+0

'Mongoid.purge!'適用於4.0.2,我認爲它比使用DatabaseCleaner更好。 –

2

加入的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/

+0

爲什麼你只是刪除你關於類變量的問題?這是一個很好的,我有一個答案給你。 –