Ruby on rails 使用Rspec+进行新线程/进程测试时数据库为空;工厂女工
在这篇博文之后 我正在尝试测试并发性。但在我的规范中,当我启动一个新线程或分叉一个进程时,我无法找到记录Ruby on rails 使用Rspec+进行新线程/进程测试时数据库为空;工厂女工,ruby-on-rails,ruby,multithreading,rspec,factory-bot,Ruby On Rails,Ruby,Multithreading,Rspec,Factory Bot,在这篇博文之后 我正在尝试测试并发性。但在我的规范中,当我启动一个新线程或分叉一个进程时,我无法找到记录 describe 'test concurrency' do let(:order_1) { create(:order) } let(:order_2) { create(:order) } let(:order_3) { create(:order) } let(:order_4) { create(:order) } let(:product) { create(:
describe 'test concurrency' do
let(:order_1) { create(:order) }
let(:order_2) { create(:order) }
let(:order_3) { create(:order) }
let(:order_4) { create(:order) }
let(:product) { create(:product) }
it 'test concurrency' do
wait_for_all_threads = true
product.update(quantity_available: 4, quantity_sold: 0, quantity_in_carts: 0)
orders = [order_1, order_2, order_3, order_4]
# Objects are persisted in here
# because order_n.persisted => true
# product.persisted => true
# product.reload works without issue (and this is essentially what causes the RecordNotFound error in Order#add_item)
threads = orders.map do |order|
Thread.new do
# Objects cannot be found in the database
true while wait_for_all_threads
item = order.add_item(product, 1)
order_items << item
end
end
wait_for_all_threads = false
threads.each(&:join)
# ...
# here comes all the expects ...
# not gonna post it because it's not what matters in this question
end
end
但是没有运气
所以问题是,在新线程中,在数据库中找不到任何创建的对象
我正在挖掘的一些线索:
- 当我通过sql客户机直接连接时,数据库一直是空的。(当我在测试中添加断点,并验证对象是否持久化时?)
- factory girl/rspec是否实际将数据提交到数据库?如果没有,那么新线程将无法读取它,因为它仍在bin日志或内存中?(这会提示我,因为我记得在提交后,
不会在rspec中运行)
self.use_transactional_tests = false
“使用事务性固定装置”已被弃用
我还必须通过以下方式绕过DatabaseCleaner:
it 'tests concurrency', bypass_cleaner: true do
end
然后在rails\u helper中(或者您有DatabaseCleaner设置的地方)
我希望这能帮助你或其他人:)嗨。。。这不是你的全部代码。。。而且肯定不是所有与这个问题相关的代码。你能给我们看一下你在数据库中实际设置对象的代码吗?另外-显示如何测试对象是否在数据库中的代码?@TarynEast当然,请参阅我的编辑。
it 'tests concurrency', bypass_cleaner: true do
end
config.around(:each) do |example|
if example.metadata[:bypass_cleaner]
example.run
else
# database cleaner code
end
end