{"id":15026765,"url":"https://github.com/databasecleaner/database_cleaner","last_synced_at":"2025-05-12T05:16:24.449Z","repository":{"id":515527,"uuid":"143489","full_name":"DatabaseCleaner/database_cleaner","owner":"DatabaseCleaner","description":"Strategies for cleaning databases in Ruby.  Can be used to ensure a clean state for testing.","archived":false,"fork":false,"pushed_at":"2025-03-10T15:18:19.000Z","size":1376,"stargazers_count":2946,"open_issues_count":26,"forks_count":484,"subscribers_count":38,"default_branch":"main","last_synced_at":"2025-05-08T00:38:33.792Z","etag":null,"topics":["database-cleaner","ruby","testing","testing-tools"],"latest_commit_sha":null,"homepage":"https://www.rubydoc.info/github/DatabaseCleaner/database_cleaner","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DatabaseCleaner.png","metadata":{"files":{"readme":"README.markdown","changelog":"History.rdoc","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2009-03-05T06:08:15.000Z","updated_at":"2025-05-04T15:12:49.000Z","dependencies_parsed_at":"2023-07-08T09:16:11.291Z","dependency_job_id":"ff4cc824-4297-444c-827f-73f21af18580","html_url":"https://github.com/DatabaseCleaner/database_cleaner","commit_stats":{"total_commits":958,"total_committers":215,"mean_commits":4.455813953488372,"dds":0.7818371607515657,"last_synced_commit":"1f5946a042231c693a8e5c303d38bb464835a699"},"previous_names":["bmabey/database_cleaner"],"tags_count":55,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DatabaseCleaner%2Fdatabase_cleaner","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DatabaseCleaner%2Fdatabase_cleaner/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DatabaseCleaner%2Fdatabase_cleaner/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DatabaseCleaner%2Fdatabase_cleaner/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DatabaseCleaner","download_url":"https://codeload.github.com/DatabaseCleaner/database_cleaner/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253170926,"owners_count":21865273,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["database-cleaner","ruby","testing","testing-tools"],"created_at":"2024-09-24T20:05:03.342Z","updated_at":"2025-05-09T00:31:18.347Z","avatar_url":"https://github.com/DatabaseCleaner.png","language":"Ruby","readme":"# Database Cleaner\n\n[![Build Status](https://github.com/DatabaseCleaner/database_cleaner/actions/workflows/ci.yml/badge.svg)](https://github.com/DatabaseCleaner/database_cleaner/actions/workflows/ci.yml)\n[![Code Climate](https://codeclimate.com/github/DatabaseCleaner/database_cleaner/badges/gpa.svg)](https://codeclimate.com/github/DatabaseCleaner/database_cleaner)\n[![codecov](https://codecov.io/gh/DatabaseCleaner/database_cleaner/branch/main/graph/badge.svg)](https://codecov.io/gh/DatabaseCleaner/database_cleaner)\n![Gem Version](https://badge.fury.io/rb/database_cleaner.svg)\n[![SemVer](https://api.dependabot.com/badges/compatibility_score?dependency-name=database_cleaner\u0026package-manager=bundler\u0026version-scheme=semver)](https://dependabot.com/compatibility-score.html?dependency-name=database_cleaner\u0026package-manager=bundler\u0026version-scheme=semver)\n\nDatabase Cleaner is a set of gems containing strategies for cleaning your database in Ruby.\n\nThe original use case was to ensure a clean state during tests.\nEach strategy is a small amount of code but is code that is usually needed in any ruby app that is testing with a database.\n\n## Gem Setup\n\nInstead of using the `database_cleaner` gem directly, each ORM has its own gem. Most projects will only need the `database_cleaner-active_record` gem:\n\n```ruby\n# Gemfile\ngroup :test do\n  gem 'database_cleaner-active_record'\nend\n```\n\nIf you are using multiple ORMs, just load multiple gems:\n\n\n```ruby\n# Gemfile\ngroup :test do\n  gem 'database_cleaner-active_record'\n  gem 'database_cleaner-redis'\nend\n```\n## List of adapters\n\nHere is an overview of the databases and ORMs supported by each adapter:\n\nMySQL, PostgreSQL, SQLite, etc\n * [database_cleaner-active_record](https://github.com/DatabaseCleaner/database_cleaner-active_record)\n * [database_cleaner-sequel](https://github.com/DatabaseCleaner/database_cleaner-sequel)\n\nMongoDB\n * [database_cleaner-mongo](https://github.com/DatabaseCleaner/database_cleaner-mongo)\n * [database_cleaner-mongoid](https://github.com/DatabaseCleaner/database_cleaner-mongoid)\n\nRedis\n * [database_cleaner-redis](https://github.com/DatabaseCleaner/database_cleaner-redis)\n\nMore details on available configuration options can be found in the README for the specific adapter gem that you're using.\n\nFor support or to discuss development please use the [Google Group](https://groups.google.com/group/database_cleaner).\n\n### Discontinued adapters\n\nThe following adapters have been discontinued. Please let us know on the [Google Group](https://groups.google.com/group/database_cleaner) if you think one of these should be resurrected!\n\n * [database_cleaner-data_mapper](https://github.com/DatabaseCleaner/database_cleaner-data_mapper)\n * [database_cleaner-couch_potato](https://github.com/DatabaseCleaner/database_cleaner-couch_potato)\n * [database_cleaner-mongo_mapper](https://github.com/DatabaseCleaner/database_cleaner-mongo_mapper)\n * [database_cleaner-moped](https://github.com/DatabaseCleaner/database_cleaner-moped)\n * [database_cleaner-neo4j](https://github.com/DatabaseCleaner/database_cleaner-neo4j)\n\n## How to use\n\n```ruby\nrequire 'database_cleaner/active_record'\n\nDatabaseCleaner.strategy = :truncation\n\n# then, whenever you need to clean the DB\nDatabaseCleaner.clean\n```\n\nWith the `:truncation` strategy you can also pass in options, for example:\n\n```ruby\nDatabaseCleaner.strategy = [:truncation, only: %w[widgets dogs some_other_table]]\n```\n\n```ruby\nDatabaseCleaner.strategy = [:truncation, except: %w[widgets]]\n```\n\n(I should point out the truncation strategy will never truncate your schema_migrations table.)\n\nSome strategies need to be started before tests are run (for example the `:transaction` strategy needs to know to open up a transaction). This can be accomplished by calling `DatabaseCleaner.start` at the beginning of the run, or by running the tests inside a block to `DatabaseCleaner.cleaning`. So you would have:\n\n```ruby\nrequire 'database_cleaner/active_record'\n\nDatabaseCleaner.strategy = :transaction\n\nDatabaseCleaner.start # usually this is called in setup of a test\n\ndirty_the_db\n\nDatabaseCleaner.clean # cleanup of the test\n\n# OR\n\nDatabaseCleaner.cleaning do\n  dirty_the_db\nend\n```\n\nAt times you may want to do a single clean with one strategy.\n\nFor example, you may want to start the process by truncating all the tables, but then use the faster transaction strategy the remaining time. To accomplish this you can say:\n\n```ruby\nrequire 'database_cleaner/active_record'\n\nDatabaseCleaner.clean_with :truncation\n\nDatabaseCleaner.strategy = :transaction\n\n# then make the DatabaseCleaner.start and DatabaseCleaner.clean calls appropriately\n```\n\n## What strategy is fastest?\n\nFor the SQL libraries the fastest option will be to use `:transaction` as transactions are simply rolled back. If you can use this strategy you should. However, if you wind up needing to use multiple database connections in your tests (i.e. your tests run in a different process than your application) then using this strategy becomes a bit more difficult. You can get around the problem a number of ways.\n\nOne common approach is to force all processes to use the same database connection ([common ActiveRecord hack](http://blog.plataformatec.com.br/2011/12/three-tips-to-improve-the-performance-of-your-test-suite/)) however this approach has been reported to result in non-deterministic failures.\n\nAnother approach is to have the transactions rolled back in the application's process and relax the isolation level of the database (so the tests can read the uncommitted transactions).\n\nAn easier, but slower, solution is to use the `:truncation` or `:deletion` strategy.\n\nSo what is fastest out of `:deletion` and `:truncation`? Well, it depends on your table structure and what percentage of tables you populate in an average test. The reasoning is out of the scope of this README but here is a [good SO answer on this topic for Postgres](https://stackoverflow.com/questions/11419536/postgresql-truncation-speed/11423886#11423886).\n\nSome people report much faster speeds with `:deletion` while others say `:truncation` is faster for them. The best approach therefore is it try all options on your test suite and see what is faster.\n\nIf you are using ActiveRecord then take a look at the [additional options](https://github.com/DatabaseCleaner/database_cleaner-active_record#strategy-configuration-options) available for `:truncation`.\n\nDatabase Cleaner also includes a `null` strategy (that does no cleaning at all) which can be used with any ORM library.\nYou can also explicitly use it by setting your strategy to `nil`.\n\n## Test Framework Examples\n\n### RSpec Example\n\n```ruby\nRSpec.configure do |config|\n\n  config.before(:suite) do\n    DatabaseCleaner.strategy = :transaction\n    DatabaseCleaner.clean_with(:truncation)\n  end\n\n  config.around(:each) do |example|\n    DatabaseCleaner.cleaning do\n      example.run\n    end\n  end\n\nend\n```\n\n### RSpec with Capybara Example\n\nYou'll typically discover a feature spec is incorrectly using transaction\ninstead of truncation strategy when the data created in the spec is not\nvisible in the app-under-test.\n\nA frequently occurring example of this is when, after creating a user in a\nspec, the spec mysteriously fails to login with the user. This happens because\nthe user is created inside of an uncommitted transaction on one database\nconnection, while the login attempt is made using a separate database\nconnection. This separate database connection cannot access the\nuncommitted user data created over the first database connection due to\ntransaction isolation.\n\nFor feature specs using a Capybara driver for an external\nJavaScript-capable browser (in practice this is all drivers except\n`:rack_test`), the Rack app under test and the specs do not share a\ndatabase connection.\n\nWhen a spec and app-under-test do not share a database connection,\nyou'll likely need to use the truncation strategy instead of the\ntransaction strategy.\n\nSee the suggested config below to temporarily enable truncation strategy\nfor affected feature specs only. This config continues to use transaction\nstrategy for all other specs.\n\nIt's also recommended to use `append_after` to ensure `DatabaseCleaner.clean`\nruns *after* the after-test cleanup `capybara/rspec` installs.\n\n```ruby\nrequire 'capybara/rspec'\n\n#...\n\nRSpec.configure do |config|\n\n  config.use_transactional_fixtures = false\n\n  config.before(:suite) do\n    if config.use_transactional_fixtures?\n      raise(\u003c\u003c-MSG)\n        Delete line `config.use_transactional_fixtures = true` from rails_helper.rb\n        (or set it to false) to prevent uncommitted transactions being used in\n        JavaScript-dependent specs.\n\n        During testing, the app-under-test that the browser driver connects to\n        uses a different database connection to the database connection used by\n        the spec. The app's database connection would not be able to access\n        uncommitted transaction data setup over the spec's database connection.\n      MSG\n    end\n    DatabaseCleaner.clean_with(:truncation)\n  end\n\n  config.before(:each) do\n    DatabaseCleaner.strategy = :transaction\n  end\n\n  config.before(:each, type: :feature) do\n    # :rack_test driver's Rack app under test shares database connection\n    # with the specs, so continue to use transaction strategy for speed.\n    driver_shares_db_connection_with_specs = Capybara.current_driver == :rack_test\n\n    unless driver_shares_db_connection_with_specs\n      # Driver is probably for an external browser with an app\n      # under test that does *not* share a database connection with the\n      # specs, so use truncation strategy.\n      DatabaseCleaner.strategy = :truncation\n    end\n  end\n\n  config.before(:each) do\n    DatabaseCleaner.start\n  end\n\n  config.append_after(:each) do\n    DatabaseCleaner.clean\n  end\n\nend\n```\n\n\n### Minitest Example\n\n```ruby\nDatabaseCleaner.strategy = :transaction\n\nclass Minitest::Spec\n  before :each do\n    DatabaseCleaner.start\n  end\n\n  after :each do\n    DatabaseCleaner.clean\n  end\nend\n\n# with the minitest-around gem, this may be used instead:\nclass Minitest::Spec\n  around do |tests|\n    DatabaseCleaner.cleaning(\u0026tests)\n  end\nend\n```\n\n### Cucumber Example\n\nIf you're using Cucumber with Rails, just use the generator that ships with cucumber-rails, and that will create all the code you need to integrate DatabaseCleaner into your Rails project.\n\nOtherwise, to add DatabaseCleaner to your project by hand, create a file `features/support/database_cleaner.rb` that looks like this:\n\n```ruby\nrequire 'database_cleaner/active_record'\n\nDatabaseCleaner.strategy = :truncation\n\nAround do |scenario, block|\n  DatabaseCleaner.cleaning(\u0026block)\nend\n```\n\nThis should cover the basics of tear down between scenarios and keeping your database clean.\n\nFor more examples see the section [\"Why?\"](#why).\n\n## How to use with multiple ORMs\n\nSometimes you need to use multiple ORMs in your application.\n\nYou can use DatabaseCleaner to clean multiple ORMs, and multiple databases for those ORMs.\n\n```ruby\nrequire 'database_cleaner/active_record'\nrequire 'database_cleaner/mongo_mapper'\n\n# How to specify particular orms\nDatabaseCleaner[:active_record].strategy = :transaction\nDatabaseCleaner[:mongo_mapper].strategy = :truncation\n\n# How to specify particular databases\nDatabaseCleaner[:active_record, db: :two]\n\n# You may also pass in the model directly:\nDatabaseCleaner[:active_record, db: ModelWithDifferentConnection]\n```\n\nUsage beyond that remains the same with `DatabaseCleaner.start` calling any setup on the different configured databases, and `DatabaseCleaner.clean` executing afterwards.\n\n## Why?\n\nOne of my motivations for writing this library was to have an easy way to turn on what Rails calls \"transactional_fixtures\" in my non-rails ActiveRecord projects.\n\nAfter copying and pasting code to do this several times I decided to package it up as a gem and save everyone a bit of time.\n\n## Safeguards\n\nDatabaseCleaner comes with safeguards against:\n\n* Running in production (checking for `ENV`, `APP_ENV`, `RACK_ENV`, and `RAILS_ENV`)\n* Running against a remote database (checking for a `DATABASE_URL` that does not include `localhost`, `.local` or `127.0.0.1`)\n\nBoth safeguards can be disabled separately as follows.\n\nUsing environment variables:\n\n```\nexport DATABASE_CLEANER_ALLOW_PRODUCTION=true\nexport DATABASE_CLEANER_ALLOW_REMOTE_DATABASE_URL=true\n```\n\nIn Ruby:\n\n```ruby\nDatabaseCleaner.allow_production = true\nDatabaseCleaner.allow_remote_database_url = true\n```\n\nIn Ruby, a URL allowlist can be specified. When specified, DatabaseCleaner will only allow `DATABASE_URL` to be equal\nto one of the values specified in the url allowlist like so:\n\n```ruby\nDatabaseCleaner.url_allowlist = ['postgres://postgres@localhost', 'postgres://foo@bar']\n```\n\nAllowlist elements are matched with case equality (`===`), so regular expressions or procs may be used:\n\n```ruby\nDatabaseCleaner.url_allowlist = [\n  %r{^postgres://postgres@localhost},         # match any db with this prefix\n  proc {|uri| URI.parse(uri).user == \"test\" } # match any db authenticating with the 'test' user\n]\n```\n\n## CHANGELOG\n\nSee [HISTORY](History.rdoc) for details.\n\n## COPYRIGHT\n\nSee [LICENSE](LICENSE) for details.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdatabasecleaner%2Fdatabase_cleaner","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdatabasecleaner%2Fdatabase_cleaner","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdatabasecleaner%2Fdatabase_cleaner/lists"}