Blog ยป Deleting all records in rails
Posted on 23 Nov 2010 17:01
If you need to run your tests without transactional fixtures then you can ensure all records are deleted after the test.
I found out that during steak/capybara tests, I cannot use transactional fixtures so I had to write a generic solution to clean up test data.
In file config/initializers/active_record_delete_everything.rb :
#config/initializers/active_record_delete_everything.rb module ActiveRecord class Base class << self def delete_everything! begin ActiveRecord::Base.connection.rollback_db_transaction rescue #Intentionally suppress exception when no trasactions end klasses = ActiveRecord::Base.connection.tables.reject { |t| t == 'schema_migrations' }.collect { |t| t.classify.constantize } klasses.each { | k | k.delete_all } end end end end
RSpec or Steak tests
In file "spec_helper.rb":
config.after(:each) do ActiveRecord::Base.delete_everything! end
Functional and Unit Tests
In file "test_helper.rb":
class ActiveSupport::TestCase ... def teardown ActiveRecord::Base.delete_everything! end end
This still applies if you're using shoulda.
If you like this page, please spread the word:
You can contact me if you have questions or corrections.


