Testing concurrency with Thread.new in RSpec

I am trying to set up a test around concurrency. The ultimate goal is to verify that the service uses ActiveRecord skips lockedrecords in PostgreSQL .

This works great in two consoles:

# 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

However, with RSpec, any code that I run in Thread.newcannot find any record, for example:

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

throws an error saying that queue.items.firstit cannot be found, and when used pryfor viewing in the stream, I do not see any elements.

How to effectively check something like this with RSpec?

+4
source share
1 answer

DatabaseCleaner, , DatabaseCleaner.strategy = :truncation .

+1

Source: https://habr.com/ru/post/1650717/


All Articles