ruby-on-rails - Database_cleaner gem 未清理

标签 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)>'

我错过了什么?

最佳答案

好吧,经过大量阅读,我开始确定 database_cleaner 和 Mongo 不能很好地协同工作。虽然它可能不是最干净的解决方案,但它很简单:

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

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

关于ruby-on-rails - Database_cleaner gem 未清理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37260724/

相关文章:

ios - RubyMotion 和指针

javascript - Mongoose深度查找查询

ruby-on-rails - 用于更改现有数据库 View 的 Rails 迁移

ruby-on-rails - 什么是 :locals for in render in rails?

ruby-on-rails - Rails - 每当 gem - 动态值

Ruby - 使用 Mechanize::File 响应而不保存到磁盘

ruby-on-rails - 由于 `require' : cannot load such file -- bcrypt_ext (LoadError),Rails 服务器无法启动

ruby-on-rails - 安装 ruby​​Mine 时出错,未指定 SDK,但已列出

mongodb - 使用基于文档的 nosql(mongodb、couchdb 和 riak 等)查询关系数据的性能

mongodb写关注: all replica members dynamically?