Database_cleaner gem不是清理工具

时间:2016-05-16 18:26:47

标签: ruby-on-rails ruby mongodb rspec

我使用Mongoid作为我的数据库并按照其他Stackoverflow问题的指示配置了我的spec_helper.rb文件,但是我仍然在后续测试中收到对象存在的错误。因此,database_cleaner并不是应该清理我的测试数据库。

这是我的spec_helper.rb

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rails/mongoid'
require 'mongoid-rspec'
require 'database_cleaner'

Mongoid.load!(Rails.root.join("config", "mongoid.yml"))

# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
RSpec.configure do |config|
  config.mock_with :rspec
  #config.use_transactional_fixtures = true
  config.infer_base_class_for_anonymous_controllers = false
  config.order = "random"

  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

我的rspec测试文件很简单:

describe Stock do
  it "should get created with only name and symbol" do
    stock = Stock.create(name: "Netflix", symbol: "NFLX")
    expect(stock.errors.full_messages).to eq []
  end
end

我在第一次运行时(在我手动重置数据库之后)使用rake db:reset RAILS_ENV=test获得的输出正常,但是在我得到之后每次运行:

Failures:

  1) Stock should get created with only name and symbol
     Failure/Error: expect(stock.errors.full_messages).to eq []

       expected: []
            got: ["Symbol is already taken"]

       (compared using ==)
     # ./spec/models/stock_spec.rb:6:in `block (2 levels) in <top (required)>'

我错过了什么?

1 个答案:

答案 0 :(得分:4)

好吧,经过更多的阅读后,我来确定database_cleaner和Mongo一起玩不好。虽然它可能不是最干净的解决方案,但很简单:

在我的spec_helper.rb文件中,我最终将此行添加到RSpec.configure块:

config.after(:each) do
  Mongoid.purge!
end