Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/database_cleaner/active_record/truncation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ def database_tables

def truncate_tables(table_names)
return if table_names.nil? || table_names.empty?
execute("TRUNCATE TABLE #{table_names.map{|name| quote_table_name(name)}.join(', ')} RESTART IDENTITY CASCADE;")
execute("TRUNCATE TABLE #{table_names.map{|name| quote_table_name(name)}.join(', ')} RESTART IDENTITY RESTRICT;")
end

def pre_count_truncate_tables(tables)
Expand Down
8 changes: 8 additions & 0 deletions spec/database_cleaner/active_record/truncation_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
before do
2.times { User.create! }
2.times { Agent.create! }
UserProfile.create!(user_id: User.first.id) if helper.db == :postgres
end

it "should truncate all tables" do
Expand All @@ -42,6 +43,13 @@
.to([0,0])
end

if helper.db == :postgres
it "should raise exception when trying to truncate table referenced in a foreign key constraint" do
expect { described_class.new(except: ['user_profiles']).clean }
.to raise_error(ActiveRecord::StatementInvalid, /cannot truncate a table referenced in a foreign key constraint/)
end
end

it "should reset AUTO_INCREMENT index of table" do
strategy.clean
expect(User.create.id).to eq 1
Expand Down
23 changes: 23 additions & 0 deletions spec/support/database_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ def self.with_all_dbs &block
def setup
Kernel.const_set "User", Class.new(ActiveRecord::Base)
Kernel.const_set "Agent", Class.new(ActiveRecord::Base)
Kernel.const_set "UserProfile", Class.new(ActiveRecord::Base) if db == :postgres

super

Expand All @@ -25,6 +26,7 @@ def teardown

Kernel.send :remove_const, "User" if defined?(User)
Kernel.send :remove_const, "Agent" if defined?(Agent)
Kernel.send :remove_const, "UserProfile" if defined?(UserProfile)
end

private
Expand All @@ -33,4 +35,25 @@ def establish_connection(config = default_config)
ActiveRecord::Base.establish_connection(config)
@connection = ActiveRecord::Base.connection
end

def load_schema
super

if db == :postgres
connection.execute <<-SQL
CREATE TABLE IF NOT EXISTS user_profiles (
user_id INTEGER,
FOREIGN KEY(user_id) REFERENCES users(id)
);
SQL
end
end

def drop_db
if db == :postgres
connection.execute "DROP TABLE IF EXISTS user_profiles"
end

super
end
end