database_cleaner-active_record icon indicating copy to clipboard operation
database_cleaner-active_record copied to clipboard

SeededDeletion Strategy for DatabaseCleaner ActiveRecord

Open jrafanie opened this issue 3 months ago • 1 comments

Hello,

Because I had a similar use case as described in https://github.com/DatabaseCleaner/database_cleaner-active_record/issues/31, I've developed a solution for running UI tests with seeded data while only cleaning records created during testing.

The SeededDeletion Strategy preserves seed data while removing test-generated records: database_cleaner-activerecord-seeded_deletion.

How It Works

The SeededDeletion class implements simple logic:

  1. When start is called, it captures the maximum ID for each table
  2. When clean is called, it only deletes rows with IDs greater than the captured maximums

This effectively preserves all pre-existing seed data while cleaning up records created during test execution.

Details

Extends the standard Deletion strategy Currently tested with PostgreSQL (though adaptable to other databases) Uses SQL to identify tables with ID columns Handles edge cases like tables without ID columns

Usage Example

DatabaseCleaner[:active_record].strategy = DatabaseCleaner::ActiveRecord::SeededDeletion.new

Future Improvements

The current implementation is functional but has room for optimization:

  • Reduce the need to visit each table in separate queries
  • Add support for other databases
  • Improve performance for larger databases
  • If it gets fast enough, the default implementation could add itself in the before/after in typical test frameworks such as minitest/rspec/cypress/etc.

Integration Question

Would the DatabaseCleaner team consider incorporating this strategy into the active_record repository, or should it remain as a standalone extension? I believe this addresses a common use case for teams working with seeded test environments.

Thank you.

jrafanie avatar Oct 10 '25 21:10 jrafanie

If there's interest, I can propose a PR to add it.

jrafanie avatar Oct 16 '25 18:10 jrafanie