bib*_*chy 6 ruby rspec ruby-on-rails database-cleaner
我有一个使用 rspec 并包含 DatabseCleaner 的 rails 应用程序,以确保每次测试之间的测试数据库都是干净的。
DatabaseCleaner 在我们的配置中spec/rails_helper.rb使用
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.around(:each) do |example|
DatabaseCleaner.cleaning do
example.run
end
end
Run Code Online (Sandbox Code Playgroud)
我们一直在 ci 环境中看到间歇性错误,其中单个测试将失败
1) LibraryHours Required fields Library Hour must have a location
Failure/Error:
DatabaseCleaner.cleaning do
example.run
end
NoMethodError:
undefined method `rollback' for nil:NilClass
# ./spec/rails_helper.rb:66:in `block (2 levels) in <top (required)>'
Run Code Online (Sandbox Code Playgroud)
我们无法使用 rspec 运行中的种子在本地重现错误,并且在调试时遇到了真正的麻烦。
DatabaseCleaner.clean因此,事实证明,开发人员(我)不明白 Rails_helper 中的 DatabaseCleaner 调用已经适用于所有规范,并且向其中一个规范文件添加了额外的调用。删除附加项:
after do
DatabaseCleaner.clean
end
Run Code Online (Sandbox Code Playgroud)
解决了这个问题。
我猜这是由两次调用引起的竞争条件DatabaseCleaner.clean。