### Minitest Integration and Strategy Configuration Source: https://context7.com/databasecleaner/database_cleaner-active_record/llms.txt Complete Minitest setup with Database Cleaner integration for efficient test data management. This example demonstrates setting the `:transaction` strategy for general tests and `:truncation` for integration tests within `ActiveSupport::TestCase` and `ActionDispatch::IntegrationTest`. ```ruby # test/test_helper.rb require 'database_cleaner-active_record' class ActiveSupport::TestCase def before_setup super DatabaseCleaner[:active_record].strategy = :transaction DatabaseCleaner[:active_record].start end def after_teardown DatabaseCleaner[:active_record].clean super end end class ActionDispatch::IntegrationTest def before_setup super # Use truncation for integration tests DatabaseCleaner[:active_record].strategy = :truncation DatabaseCleaner[:active_record].start end def after_teardown DatabaseCleaner[:active_record].clean super end end # Example test class UserTest < ActiveSupport::TestCase test "creates user successfully" do user = User.create!(name: "Test User", email: "test@example.com") assert_equal 1, User.count assert_equal "Test User", user.name end end ``` -------------------------------- ### RSpec Integration and Strategy Configuration Source: https://context7.com/databasecleaner/database_cleaner-active_record/llms.txt Complete RSpec setup with different cleaning strategies for various test types. This example shows how to configure Database Cleaner to use `:truncation` for feature and JavaScript tests, and `:transaction` for standard model tests. It includes before and after hooks for `RSpec.configure`. ```ruby # spec/spec_helper.rb require 'database_cleaner-active_record' RSpec.configure do |config| config.before(:suite) do DatabaseCleaner.clean_with(:truncation) end config.before(:each) do DatabaseCleaner.strategy = :transaction end config.before(:each, type: :feature) do # Use truncation for feature tests that run in separate processes DatabaseCleaner.strategy = :truncation end config.before(:each, js: true) do # Use truncation for JavaScript tests DatabaseCleaner.strategy = :truncation end config.before(:each) do DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean end end # Example test using the configuration RSpec.describe User, type: :model do it "creates a user" do user = User.create!(name: "Test User", email: "test@example.com") expect(User.count).to eq(1) end # Database automatically cleaned after each test end RSpec.describe "User registration", type: :feature, js: true do it "allows user signup" do visit "/signup" fill_in "Name", with: "New User" fill_in "Email", with: "new@example.com" click_button "Sign Up" expect(User.count).to eq(1) end # Uses truncation strategy automatically end ``` -------------------------------- ### Performance Optimization with `pre_count` Source: https://context7.com/databasecleaner/database_cleaner-active_record/llms.txt Optimize database cleaning performance by skipping empty tables using the `pre_count` option. This example demonstrates how to enable `pre_count` and benchmarks the performance difference compared to cleaning without it, showing significant improvements when many tables are empty. ```ruby # Enable pre_count to check tables before cleaning DatabaseCleaner[:active_record].strategy = DatabaseCleaner::ActiveRecord::Truncation.new( pre_count: true, cache_tables: true ) # Benchmark example require 'benchmark' # Without pre_count DatabaseCleaner[:active_record].strategy = :truncation time_without = Benchmark.realtime do 100.times { DatabaseCleaner[:active_record].clean } end # With pre_count optimization DatabaseCleaner[:active_record].strategy = DatabaseCleaner::ActiveRecord::Truncation.new( pre_count: true ) time_with = Benchmark.realtime do 100.times { DatabaseCleaner[:active_record].clean } end puts "Without pre_count: #{time_without}s" puts "With pre_count: #{time_with}s" # Significant improvement when many tables are empty ``` -------------------------------- ### Initialize Database Cleaner with RSpec Configuration Source: https://context7.com/databasecleaner/database_cleaner-active_record/llms.txt Sets up Database Cleaner in a test suite with default transaction strategy and before/around hooks. Configures the gem to use transaction-based cleanup for test isolation with an initial truncation to ensure a clean starting state. ```ruby # spec/spec_helper.rb or test/test_helper.rb require 'database_cleaner-active_record' RSpec.configure do |config| config.before(:suite) do DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with(:truncation) end config.around(:each) do |example| DatabaseCleaner.cleaning do example.run end end end ``` -------------------------------- ### Install database_cleaner-active_record Gem Source: https://github.com/databasecleaner/database_cleaner-active_record/blob/main/README.md This snippet shows how to add the database_cleaner-active_record gem to your project's Gemfile for testing purposes. It assumes a standard Rails environment where the Gemfile is used for dependency management. ```ruby # Gemfile group :test do gem 'database_cleaner-active_record' end ``` -------------------------------- ### PostgreSQL Specific Configuration for Schemas and Constraints Source: https://context7.com/databasecleaner/database_cleaner-active_record/llms.txt Handle PostgreSQL-specific features like schemas and foreign key constraints using Database Cleaner. This includes suppressing NOTICE messages, using the `:cascade` option for truncating tables with foreign keys, and configuring for multi-tenant setups with schema switching. ```ruby # Suppress NOTICE messages for cascading truncates # Add to database.yml: # test: # adapter: postgresql # database: myapp_test # min_messages: WARNING # Use cascade option to handle foreign key constraints DatabaseCleaner[:active_record].strategy = DatabaseCleaner::ActiveRecord::Truncation.new( truncate_option: :cascade, cache_tables: false # Disable if using schema switching ) # For multi-tenant setups with Postgres schemas DatabaseCleaner[:active_record].strategy = DatabaseCleaner::ActiveRecord::Truncation.new( cache_tables: false, # Required when changing schemas except: ["shared_data_table"] ) # Example with schema switching DatabaseCleaner[:active_record].cleaning do # Switch schema ActiveRecord::Base.connection.schema_search_path = "tenant1" User.create!(name: "Tenant 1 User") # Tables in tenant1 schema will be cleaned end ``` -------------------------------- ### Configure Custom Database File Location Source: https://context7.com/databasecleaner/database_cleaner-active_record/llms.txt Specify a custom database configuration file location for non-standard Rails setups. This allows you to use a different `database.yml` file and configure database connections accordingly. It is essential for projects with unique directory structures or multiple database configurations. ```ruby # Set custom config file location DatabaseCleaner::ActiveRecord.config_file_location = "/custom/path/to/database.yml" # Now configure with database symbol from that file DatabaseCleaner[:active_record].db = :test DatabaseCleaner[:active_record].strategy = :transaction DatabaseCleaner[:active_record].clean # Reset to default DatabaseCleaner::ActiveRecord.config_file_location = "#{Dir.pwd}/config/database.yml" ``` -------------------------------- ### Configure Transaction Strategy for Fast Test Cleanup Source: https://context7.com/databasecleaner/database_cleaner-active_record/llms.txt Demonstrates transaction-based database cleaning using manual start/clean methods and block form. This strategy rolls back database transactions for rapid test isolation without modifying table structures. ```ruby # Configure transaction strategy (default) DatabaseCleaner[:active_record].strategy = :transaction # Manual start and clean DatabaseCleaner[:active_record].start # ... run your tests that create/modify data User.create!(name: "John Doe", email: "john@example.com") Post.create!(title: "Test Post", user_id: 1) DatabaseCleaner[:active_record].clean # Or use the block form DatabaseCleaner[:active_record].cleaning do User.create!(name: "Jane Doe", email: "jane@example.com") expect(User.count).to eq(1) end # Database is automatically cleaned after block expect(User.count).to eq(0) ``` -------------------------------- ### Configure Multiple Database Connections Source: https://context7.com/databasecleaner/database_cleaner-active_record/llms.txt Sets up separate cleaning strategies for multiple ActiveRecord database connections. Each database can have its own strategy and configuration, allowing fine-grained control over test cleanup across complex database architectures. ```ruby # Configure for default database DatabaseCleaner[:active_record].strategy = :transaction # Configure for separate logging database DatabaseCleaner[:active_record, db: :logs].strategy = :truncation # Configure for analytics database with specific options DatabaseCleaner[:active_record, db: :analytics].strategy = DatabaseCleaner::ActiveRecord::Deletion.new( except: ["dimension_tables"], reset_ids: false ) # Clean all configured databases DatabaseCleaner[:active_record].clean DatabaseCleaner[:active_record, db: :logs].clean DatabaseCleaner[:active_record, db: :analytics].clean # Or set database by symbol defined in database.yml DatabaseCleaner[:active_record].db = :logs DatabaseCleaner[:active_record].clean ``` -------------------------------- ### Configure Truncation Strategy with Table Filtering Source: https://context7.com/databasecleaner/database_cleaner-active_record/llms.txt Sets up truncation-based cleaning with options to exclude or include specific tables, enable pre_count optimization, and configure database-specific options like PostgreSQL CASCADE. Useful for multi-process tests where transactions aren't available. ```ruby # Truncate all tables except specified ones DatabaseCleaner[:active_record].strategy = DatabaseCleaner::ActiveRecord::Truncation.new( except: ["users", "countries", "currencies"] ) DatabaseCleaner[:active_record].clean # Truncate only specific tables DatabaseCleaner[:active_record].strategy = DatabaseCleaner::ActiveRecord::Truncation.new( only: ["posts", "comments", "likes"] ) DatabaseCleaner[:active_record].clean # Enable pre_count optimization to skip empty tables DatabaseCleaner[:active_record].strategy = DatabaseCleaner::ActiveRecord::Truncation.new( pre_count: true, cache_tables: true ) DatabaseCleaner[:active_record].clean # PostgreSQL-specific cascade option DatabaseCleaner[:active_record].strategy = DatabaseCleaner::ActiveRecord::Truncation.new( truncate_option: :cascade # or :restrict (default) ) DatabaseCleaner[:active_record].clean ``` -------------------------------- ### Specify Database Connection for Cleaning Source: https://github.com/databasecleaner/database_cleaner-active_record/blob/main/README.md This demonstrates how to configure Database Cleaner to use a specific ActiveRecord database connection for cleaning operations. It shows how to assign a named connection (e.g., :logs) or revert to the default connection. ```ruby # ActiveRecord connection key DatabaseCleaner[:active_record].db = :logs # Back to default: DatabaseCleaner[:active_record].db = :default # Multiple databases can be specified: DatabaseCleaner[:active_record, db: :default] DatabaseCleaner[:active_record, db: :logs] ``` -------------------------------- ### Configure Truncation Strategy with :only Option Source: https://github.com/databasecleaner/database_cleaner-active_record/blob/main/README.md This code configures the Database Cleaner to use the truncation strategy, but only for the 'users' table. This is useful when you want to selectively clean specific tables, leaving others untouched. It demonstrates how to pass options to the strategy. ```ruby # Only truncate the "users" table. DatabaseCleaner[:active_record].strategy = DatabaseCleaner::ActiveRecord::Truncation.new(only: ["users"]) ``` -------------------------------- ### Configure Postgres Client Min Messages Source: https://github.com/databasecleaner/database_cleaner-active_record/blob/main/README.md This snippet shows how to configure the `client_min_messages` setting in `postgresql.conf` to filter out NOTICE messages. This is useful for reducing STDERR noise from operations like foreign key constraint cascades. ```sql client_min_messages = warning ``` -------------------------------- ### Handle Missing Database Connection with Retry Logic Source: https://context7.com/databasecleaner/database_cleaner-active_record/llms.txt Catches ActiveRecord::ConnectionNotEstablished exceptions and re-establishes the database connection before retrying the clean operation. This pattern prevents test failures due to transient connection issues and ensures DatabaseCleaner can execute successfully after connection recovery. ```Ruby begin DatabaseCleaner[:active_record].strategy = :transaction DatabaseCleaner[:active_record].clean rescue ActiveRecord::ConnectionNotEstablished => e puts "Database not connected: #{e.message}" ActiveRecord::Base.establish_connection retry end ``` -------------------------------- ### Configure Deletion Strategy with ID Reset Source: https://context7.com/databasecleaner/database_cleaner-active_record/llms.txt Implements deletion-based cleaning with automatic ID sequence reset for predictable primary keys across tests. Supports table exclusions and pre_count optimization for performance tuning. ```ruby # Delete all records and reset auto-increment IDs DatabaseCleaner[:active_record].strategy = DatabaseCleaner::ActiveRecord::Deletion.new( reset_ids: true ) DatabaseCleaner[:active_record].cleaning do user1 = User.create!(name: "First User") expect(user1.id).to eq(1) end # After cleaning with reset_ids, IDs start from 1 again DatabaseCleaner[:active_record].cleaning do user2 = User.create!(name: "Second User") expect(user2.id).to eq(1) # ID is reset end # Delete with table exclusions DatabaseCleaner[:active_record].strategy = DatabaseCleaner::ActiveRecord::Deletion.new( except: ["users", "roles"], reset_ids: true, pre_count: true ) DatabaseCleaner[:active_record].clean ``` -------------------------------- ### Configure Deletion Strategy with :except Option Source: https://github.com/databasecleaner/database_cleaner-active_record/blob/main/README.md This code sets up the Database Cleaner to use the deletion strategy, excluding the 'users' table from the cleanup process. This allows for targeted data removal, ensuring specific tables are preserved. It shows the usage of the :except option. ```ruby # Delete all tables except the "users" table. DatabaseCleaner[:active_record].strategy = DatabaseCleaner::ActiveRecord::Deletion.new(except: ["users"]) ``` -------------------------------- ### Handle Adapter-Specific Errors with Fallback Strategy Source: https://context7.com/databasecleaner/database_cleaner-active_record/llms.txt Attempts to use adapter-specific cleaning options like reset_ids, and falls back to a simpler deletion strategy if the adapter doesn't support those options. This ensures compatibility across different database adapters (PostgreSQL, MySQL, SQLite) without failing on unsupported features. ```Ruby begin DatabaseCleaner[:active_record].strategy = DatabaseCleaner::ActiveRecord::Deletion.new( reset_ids: true ) DatabaseCleaner[:active_record].clean rescue => e # Some adapters may not support reset_ids puts "Error: #{e.message}" DatabaseCleaner[:active_record].strategy = :deletion DatabaseCleaner[:active_record].clean end ``` -------------------------------- ### Ensure Cleanup Execution Using Rescue/Ensure Blocks Source: https://context7.com/databasecleaner/database_cleaner-active_record/llms.txt Wraps test code in a method that guarantees DatabaseCleaner cleanup runs via an ensure block, even if the test raises an exception. This pattern prevents database pollution and maintains test isolation by ensuring clean state is always restored after test execution, whether successful or failed. ```Ruby def with_database_cleanup DatabaseCleaner[:active_record].start yield rescue => e puts "Test error: #{e.message}" raise ensure DatabaseCleaner[:active_record].clean end with_database_cleanup do User.create!(name: "Test") raise "Simulated error" end # Database is still cleaned despite error ``` -------------------------------- ### Configure Database Cleaner Postgres Min Messages Source: https://github.com/databasecleaner/database_cleaner-active_record/blob/main/README.md This snippet demonstrates how to set the `min_messages` parameter within the `database.yml` file for the 'test' environment. This configuration silences specific database notices when using the Database Cleaner gem with a PostgreSQL adapter. ```yaml test: adapter: postgresql # ... min_messages: WARNING ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.