使用新的Rails / MongoID应用程序配置RSpec

时间:2011-04-28 22:13:35

标签: ruby-on-rails rspec mongoid

我正在开始一个新的应用程序并注意到我上次从头开始构建MongoID应用程序时缺少一些文档。也就是说,他们过去常常在不再存在http://mongoid.org/docs/integration/的页面上建议包含一些代码来删除MongoID的集合(在测试之后)。

现场不再提及...... 这是否(****以下)不再被视为必要或良好做法?!

#spec/spec_helper.rb:
...
RSpec.configure do |config|

  config.mock_with :rspec

  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  #config.fixture_path = "#{::Rails.root}/spec/fixtures"

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  #config.use_transactional_fixtures = true

  # Below from <http://mongoid.org/docs/integration/>  ****
  config.after :suite do
    Mongoid.master.collections.select do |collection|
      collection.name !~ /system/
    end.each(&:drop)
  end
end

3 个答案:

答案 0 :(得分:12)

这似乎也适用于Rails3并且更加整洁

config.before :each do
  Mongoid.purge!
end

它不需要额外的GEM。

答案 1 :(得分:11)

修改文件 spec / spec_helper.rb 以添加此内容:

RSpec.configure do |config|
  # Other things

  # Clean up the database
  require 'database_cleaner'
  config.before(:suite) do
    DatabaseCleaner.strategy = :truncation
    DatabaseCleaner.orm = "mongoid"
  end

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

答案 2 :(得分:2)

你可以继续做(尽管可能会切换到套件之前) - 虽然DatabaseCleaner gem很不错。

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

  config.before(:each) do
    DatabaseCleaner.start
  end

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