[rspec-users] Database clearing

Scott Taylor mailing_lists at railsnewbie.com
Sat Sep 20 20:05:03 EDT 2008


On Sep 20, 2008, at 7:18 PM, Ben Mabey wrote:

> 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|

Yeah, that's just a cleaner way of doing it - I'm sure if you tailed  
your logs you'd find a 'SHOW TABLES'

>
>  ActiveRecord::Base.connection.execute("TRUNCATE TABLE  
> #{table_name};")

Seems like you might also want to add a truncate_table method onto  
ActiveRecord::Base.

>
> 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;")
>

Nice.

Scott



More information about the rspec-users mailing list