[rspec-users] Database clearing

Ben Mabey ben at benmabey.com
Sat Sep 20 19:18:38 EDT 2008


Todd Tyree wrote:
> Ok, here's what I've come up with on the spur of the moment (goes in
> spec_helper.rb):
>
>  config.after(:each) do
>     result = ActiveRecord::Base.connection.execute('SHOW TABLES;')
>     while table = result.fetch_row
>       # Or whatever you think is appropriate.
>       next if table.index('schema_migrations') or table.index('roles')
>       ActiveRecord::Base.connection.execute("TRUNCATE #{table}")
>     end
>   end
>

I've used a similar method before.. However, your 'SHOW TABLES' and next
is not needed:

(ActiveRecord::Base.connection.tables - %w{schema_migrations}).each do
|table_name|
  ActiveRecord::Base.connection.execute("TRUNCATE TABLE #{table_name};")
 end


Also, to address Pat's statement about FKs... if ordering the truncates
is too cumbersome you could just turn off the FK checks:

ActiveRecord::Base.connection.execute("SET FOREIGN_KEY_CHECKS = 0;")
(ActiveRecord::Base.connection.tables - %w{schema_migrations}).each do
|table_name|
  ActiveRecord::Base.connection.execute("TRUNCATE TABLE #{table_name};")
 end
ActiveRecord::Base.connection.execute("SET FOREIGN_KEY_CHECKS = 1;")

(this is for mysql...)

-Ben




More information about the rspec-users mailing list