Skip to content

Commit 18a4116

Browse files
committed
Isolate "truncate_tables" method
* when the unit tests are executed in parallel (typically 4 processes), there can be a race condition when truncating the tables (resulting in "Cannot truncate a table referenced in a foreign key constraint") because "SET FOREIGN_KEY_CHECKS = x" is executed concurrently
1 parent 9930856 commit 18a4116

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

spec/support/table_truncator.rb

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
require 'mutex_m'
2+
13
class TableTruncator
24
def initialize(db, tables=nil)
35
@db = db
@@ -9,16 +11,19 @@ def self.isolated_tables(db)
911
end
1012

1113
def truncate_tables
12-
referential_integrity = ReferentialIntegrity.new(db)
13-
referential_integrity.without do
14-
case db.database_type
15-
when :postgres
16-
tables.each do |table|
17-
db.run("TRUNCATE TABLE #{table} RESTART IDENTITY CASCADE;")
18-
end
19-
when :mysql
20-
tables.each do |table|
21-
db.run("TRUNCATE TABLE #{table};")
14+
@mutex ||= Mutex.new
15+
@mutex.synchronize do
16+
referential_integrity = ReferentialIntegrity.new(db)
17+
referential_integrity.without do
18+
case db.database_type
19+
when :postgres
20+
tables.each do |table|
21+
db.run("TRUNCATE TABLE #{table} RESTART IDENTITY CASCADE;")
22+
end
23+
when :mysql
24+
tables.each do |table|
25+
db.run("TRUNCATE TABLE #{table};")
26+
end
2227
end
2328
end
2429
end

0 commit comments

Comments
 (0)