gpt4 book ai didi

ruby-on-rails - 在 RSpec 中使用 Thread.new 测试并发性

转载 作者:数据小太阳 更新时间:2023-10-29 07:37:26 25 4
gpt4 key购买 nike

我正在尝试围绕并发设置测试。最终目标是测试使用 ActiveRecord 的服务 skips locked records in PostgreSQL .

这在两个控制台中运行良好:

# in console 1
queue = MyFancyQueue.first
item_1 = queue.items.first
item_1.with_lock { sleep 30 } # locks item_1 for 30 seconds

# in console 2, while item_1 is locked
queue = MyFancyQueue.first
queue.items.first # => item_1
queue.items.lock('FOR UPDATE SKIP LOCKED').first # => item_2

但是,使用 RSpec,我在 Thread.new 中运行的任何代码都找不到任何记录,例如:

let(:queue) { MyFancyQueue.create }
let!(:items) { create_list(:item, 2, queue: queue) }

context 'with first item locked' do
it 'returns the second item' do
Thread.new { queue.items.first.with_lock { sleep 30 } }

expect(queue.items.lock('FOR UPDATE SKIP LOCKED').first).to eq items.last
end
end

会抛出一个错误,说找不到queue.items.first,当使用pry查看线程时,我看不到任何项目.

我如何使用 RSpec 有效地测试这样的东西?

最佳答案

如果您使用 DatabaseCleaner,请确保 DatabaseCleaner.strategy = :truncation 用于此测试。

关于ruby-on-rails - 在 RSpec 中使用 Thread.new 测试并发性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38858976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com