-
Notifications
You must be signed in to change notification settings - Fork 7
Using DatabaseCleaner with RSpec in a sharded test suite
Henrique Gubert edited this page Nov 22, 2016
·
1 revision
Add this to your config/initializers/rails-sharding.rb
, so you have a generic shardable model (**database_cleaner **gem requires a model through which it can access the databases)
class ShardableActiveRecordBase < ActiveRecord::Base
include Rails::Sharding::ShardableModel
end
Now add the following to your RSpec configuration:
RSpec.configure do |config|
config.before(:suite) do
DatabaseCleaner.add_cleaner(:active_record, model: ShardableActiveRecordBase)
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each, :js => true) do
# the driver we're using for js tests (poltergeist) does not share db connection with our
# specs, therefore we cannot use a transaction strategy
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
Rails::Sharding.for_each_shard do |shard_group, shard_name|
Rails::Sharding.using_shard(shard_group, shard_name) do
DatabaseCleaner.start
end
end
end
config.after(:each) do
DatabaseCleaner.clean
Rails::Sharding.for_each_shard do |shard_group, shard_name|
Rails::Sharding.using_shard(shard_group, shard_name) do
DatabaseCleaner.clean
end
end
end
end
This will basically iterate through all the shards of all shard groups, activating the database cleaner. If you don't want to always clear all shards of all shard groups you can customize the code above.