在Rails 4上使用Rspec和Mongoid 5.0清理或重置测试数据库

时间:2015-08-12 14:55:59

标签: ruby-on-rails mongodb mongoid

当我运行我的rspec测试时,许多因我的mongodb数据库中的陈旧数据而失败。 AFAIK用干净的数据库进行测试要好得多。

如何在每次测试前清理和/或重新播种数据库?

2 个答案:

答案 0 :(得分:3)

您可以使用database_cleaner gem来完成此任务。

从他们的文件:

RSpec.configure do |config|

  config.use_transactional_fixtures = false

  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do |example|
    DatabaseCleaner.strategy= :truncation
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

end

当您使用Mongoid ORM时,您可能还需要明确指定它:

# How to setup your ORM explicitly
DatabaseCleaner[:mongoid].strategy = :truncation

更新

我看到open issue for MongoID 5

为了使它工作,你可以修补问题中提到的Mongo Ruby驱动程序类。

module Mongo
  class Collection
    class View
      def remove_all
        remove(0)
      end
    end
  end
end

虽然它不是一个好的解决方案!

答案 1 :(得分:2)

问题的解决方法是在database_cleaner(1.4.1)gem的master分支中。从master安装gem以解决问题(直到版本崩溃)。预计将在下一版本中修复。

gem 'database_cleaner', :git => 'https://github.com/DatabaseCleaner/database_cleaner.git'