Skip to content

Instantly share code, notes, and snippets.

@nicoolas25
Forked from fxn/forked_specs.rb
Created May 5, 2020 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicoolas25/39488e90f5fef09ac569cb0e58dc47a6 to your computer and use it in GitHub Desktop.
Save nicoolas25/39488e90f5fef09ac569cb0e58dc47a6 to your computer and use it in GitHub Desktop.
module ForkedSpecs
def forked_specs(*specs)
ActiveRecord::Base.clear_all_connections!
pids = []
specs.each do |spec|
pids << fork do
ActiveRecord::Base.establish_connection
spec.call
end
end
pids.each do |pid|
Process.wait(pid)
$?.should be_success, 'expected forked spec to succeed'
end
ensure
ActiveRecord::Base.establish_connection
end
end
require 'fileutils'
require 'timeout'
class IPCMessage
class << self
def clean
FileUtils.rm_f(Dir.glob(file_name('*')))
end
def broadcast(message)
FileUtils.touch(file_name(message))
end
def wait_for(message)
Timeout.timeout(5) do
sleep 0.001 until broadcasted?(message)
FileUtils.rm_f(file_name(message))
end
rescue
raise "timed out waiting for IPC message #{message}"
end
def broadcasted?(message)
File.exists?(file_name(message))
end
def file_name(message)
"#{Rails.root}/tmp/ipc_message_#{message}"
end
end
end
it 'handles stale records', forked: true do
s1 = -> do
IPCMessage.wait_for(:parallel_deposit)
@ca.withdraw!(25)
@ca.credit.should == 76
end
s2 = -> do
@ca.deposit!(1).should be_true
IPCMessage.broadcast(:parallel_deposit)
end
forked_specs(s1, s2)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment