God*_*a74 1 ruby rspec ruby-on-rails mongodb
我使用 Mongoid 作为我的数据库,并spec_helper.rb按照其他 Stackoverflow 问题的说明配置了我的文件,但是我仍然收到一个错误,即在后续测试中存在对象。所以,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
Run Code Online (Sandbox Code Playgroud)
我的 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
Run Code Online (Sandbox Code Playgroud)
我得到的输出在第一次运行时很好(在我手动重置数据库之后),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)>'
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
好吧,经过大量阅读后,我确定 database_cleaner 和 Mongo 不能很好地协同工作。虽然它可能不是最干净的解决方案,但它很简单:
在我的spec_helper.rb文件中,我最终将此行添加到RSpec.configure块中:
config.after(:each) do
Mongoid.purge!
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
325 次 |
| 最近记录: |