【发布时间】:2016-05-16 18:26:46
【问题描述】:
我使用 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)>'
我错过了什么?
【问题讨论】:
标签: ruby-on-rails ruby mongodb rspec