rainkinz
rainkinz

Reputation: 10394

Testing using ActiveRecord's Multi Database Feature

Say I have a production db setup that uses 2 databases:

production:
  user_db:
    <<: *main_default
    host: ***
  animals_db:
    <<: *main_default
    host: ***

Then I have an AnimalRecord that looks like this:

class AnimalRecord < ApplicationRecord

  self.abstract_class = true

  
  connects_to database: { writing: :animals_db, reading: :animals_db }
end

and a Dog class that looks like

class Dog < AnimalRecord
end

Since they share the same schema when testing, I could just use the same db. I tried setting up database.yml like this:

test:
  database: animals_test
  host: ***
  ...

But of course I get an error when trying query a Dog because there is no connection defined for animals_db

ActiveRecord::AdapterNotSpecified:
  The `animals_db` database is not configured for the `test` environment.

If I try to create a connection that points to the same db like this:

test:
  user_db:
    database: animals_test
    ...
  animals_db:
    database: animals_test
    ...

my tests work when using database_cleaner with a truncation strategy, but it's very slow. With transactions I get duplicate key errors.

I can work around having to configure multiple databases by defining my AnimalRecord like this:

class AnimalRecord < ApplicationRecord

  self.abstract_class = true

  unless ['test', 'development'].include?(Rails.env)
    connects_to database: { writing: :oem_db, reading: :oem_db }
  end
end

however it feels wrong. My question is, do you just create multiple databases for test replicating the connects_to settings in the parent class (AnimalRecord in my case), or do you do something else?

Upvotes: 0

Views: 106

Answers (0)

Related Questions