All proposed solutions require loading the Rails environment, which in most cases is not the desired behavior due to very high overhead and very low speed. DatabaseCleaner gem is also quite slow, and it adds another dependency to your application.
After much grief and frustration for the reasons given above, I finally found the following solution exactly in what I needed. It is good, simple and fast. In spec_helper.rb :
config.after :all do ActiveRecord::Base.subclasses.each(&:delete_all) end
The best part is this: it will clear only those tables that you have effectively touched (pristine models will not be loaded and therefore will not appear in subclasses , also the reason why this does not happen before ). In addition, it is performed after tests, so green dots (hopefully) will be displayed immediately.
The only drawback to this is that if you have a dirty database before running the tests, it will not be cleared. But I doubt that this is a serious problem, since the test database usually does not apply to external tests.
Edit
Having seen that this answer gained some popularity, I wanted to edit it for completeness: if you want to clear all tables, even those that have not been touched, you should do something like “hacks” below.
Hack 1 - preload all models for subclasses method
Evaluate this before calling subclasses :
Dir[Rails.root.join("app", "models", "**", "*.rb")].each(&method(:require))
Please note that this method may take some time!
Hack 2 - manual truncation of tables
ActiveRecord::Base.connection.tables.keep_if{ |x| x != 'schema_migrations' }
you will get all the table names with which you can do something like:
case ActiveRecord::Base.configurations[Rails.env]["adapter"] when /^mysql/, /^postgresql/ ActiveRecord::Base.connection.execute("TRUNCATE #{table_name}") when /^sqlite/ ActiveRecord::Base.connection.execute("DELETE FROM #{table_name}") ActiveRecord::Base.connection.execute("DELETE FROM sqlite_sequence where name='#{table_name}'") end