如何使用MongoDB和Mongoid在Rails 3上进行适当的数据库测试(TDD)

如何通过Mongoid on Rails使用MongoDB编写适当的unit testing(以及针对该问题的集成测试)?

我问,因为与使用SQLite3相反,即使在运行测试时,我所做的一切仍然存在。 所以目前我正在编写创建测试,然后手动删除我所做的一切。 但是对于集成测试来说,它变得很烦人甚至很复杂。

我做的样本:

before(:each) do @user = User.create!(@attr) end after(:each) do # MongoDB is not a transactional DB, so added objects (create) during tests can't be rollbacked # checking for the existance of a similar object with exact :name and :email (regex make it case insensitive) cleanup = User.where(:name => "Example User", :email => /^user@example.com/i) cleanup.destroy unless cleanup.nil? end 

知道如何在测试期间使MongoDB不持久吗? (我甚至无法在沙盒模式下运行控制台,因为使用Mongoid我必须停用Active Record)。

没有办法让MongoDB非持久化。 您只需在每次测试之前或之后删除数据。 这里有一些文档:

http://www.mongodb.org/display/DOCS/Rails+-+Getting+Started#Rails-GettingStarted-Testing

好的,谢谢凯尔指出我正确的方向,我发现了如何使它工作。

所以基本上诀窍是将你所有的集合放在mongodb中,用于你将运行的每个测试用例。 这有点激进,但它确实有效。 但请记住,您在测试数据库中根本不会保留任何数据。

最后我找到了链接: http : //adventuresincoding.com/2010/07/how-to-configure-cucumber-and-rspec-to-work-with-mongoid

基本上你需要做的就是简单:

在spec_helper.rb中添加一个块:

 RSpec.configure do |config| # blabla other confs config.before :each do Mongoid.master.collections.select {|c| c.name !~ /system/ }.each(&:drop) end # blabla other confs end 

对于Mongoid 3:

  Mongoid.default_session.collections.select {|c| c.name !~ /system/ }.each(&:drop 

这有效地杀死了数据库中的所有集合,允许您每次都运行新的测试。

亚历克斯

另一种方法是使用database_cleaner 。 它支持多个ORM,所以我认为你可以这样做:

 # spec/support/database_cleaner.rb RSpec.configure do |config| 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 end 

这就是我所做的(使用Test :: Unit和Mongoid 3)……

 # test/test_helper.rb setup { Mongoid.default_session.collections.select {|c| c.name !~ /system/ }.each(&:drop) } 

这个对我有用。

spec_helper.rb ,在RSpec.configure do |config|RSpec.configure do |config| 我放:

 config.before :each do Mongoid.purge! end 

参考。