【问题标题】:Configuring RSpec with new Rails/MongoID application使用新的 Rails/MongoID 应用程序配置 RSpec
【发布时间】:2011-04-28 22:13:35
【问题描述】:

我正在启动一个新应用程序,并注意到我上次从头开始构建 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

【问题讨论】:

    标签: ruby-on-rails rspec mongoid


    【解决方案1】:

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

    config.before :each do
      Mongoid.purge!
    end
    

    不需要额外的GEM。

    【讨论】:

    • 一旦有人验证了这一点(我目前没有活动的 MongoID 项目可以尝试),我将把复选标记移到此处,因为这看起来更简单。
    • 它有效,但有一个警告:Mongoid.purge!还将删除所有索引。这意味着任何依赖具有 unique:true 的索引的规范都将失败。解决方法是在调用 purge 之后立即在每个模型类上调用 create_indexes。
    【解决方案2】:

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

    RSpec.configure 做 |config| # 其他事情 # 清理数据库 需要'database_cleaner' config.before(:suite) 做 DatabaseCleaner.strategy = :truncation DatabaseCleaner.orm = "mongoid" 结尾 config.before(:each) 做 数据库清理器.clean 结尾 结尾

    【讨论】:

    • 不适用于 Mongoid 4.0 和 rspec-core 2.14.7。我在下面使用@Jan 解决方案
    【解决方案3】:

    您可以继续这样做(尽管可能切换到之前的套件)——尽管 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
    

    【讨论】:

      猜你喜欢
      • 2013-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-10
      • 1970-01-01
      • 2011-07-28
      • 1970-01-01
      相关资源
      最近更新 更多