[rspec-users] How to test an app with multiple databases?

Ben Mabey ben at benmabey.com
Sun Mar 7 22:53:06 EST 2010

David Chelimsky wrote:
> On Sun, Mar 7, 2010 at 10:11 AM, Russell Fine <lists at ruby-forum.com> wrote:
>> David Chelimsky wrote:
>>> On Sun, Mar 7, 2010 at 9:45 AM, Russell Fine <lists at ruby-forum.com>
>>> wrote:
>>>> Our app connects to two databases. �The main database (through
>>>> ActiveRecord::Base) is automatically cleared before each test. �How do I
>>>> force the clear of the secondary database as well ?
>>> There's no implicit support for this, so you'd have to do something
>>> manually in a before(:each) block. You can do that in the
>>> configuration (usually in spec_helper):
>>> Spec::Runner.configure do |c|
>>>   c.before(:each) do
>>>     # clear out 2ndary db
>>>   end
>>> end
>>> HTH,
>>> David
>> Thanks for the quick reply.  Do you happen to know where in the
>> framework I would call to clear out the db?  I can obviously do it
>> myself by hand by just deleting all elements, but I'm worried that the
>> testing framework may perform some unique actions that differ from what
>> I would do.
> rspec-rails just wraps the rails testing framework facilities, so
> whatever you're looking for is going to be found in the rails code.
> I'm not sure how the database_cleaner gem handles multiple databases,
> but you might find your answer there.
> Can anybody else point Russell in the right direction?

DatabaseCleaner doesn't support multiple databases ATM.  I have had some 
discussions with people about adding support for multiple database types 
(i.e. AR and MongoMapper in the same app) but haven't thought about 
multiple DB connections for the same adapter.  Off the top of my head I 
don't think it should be too difficult to do for AR.  It sounds like you 
are using the standard rails transactional rollbacks for your tests 
right now.  In order to clear out your second database in a similar 
fashion (with transactions) I would try something like this in your 

require 'database_cleaner'
DatabaseCleaner.strategy = :transaction

Spec::Runner.configure do |c|
  c.before(:each) do
    ActiveRecord::Base::establish_connection :secondary_db
    ActiveRecord::Base::establish_connection :primary_db

  c.after(:each) do
    ActiveRecord::Base::establish_connection :secondary_db
    ActiveRecord::Base::establish_connection :primary_db


I haven't tried the above code but it seems correct.  Give it a try and let me know if it works.  If it does I could add support to DatabaseCleaner so you can select which AR DB connections you want to clean.


More information about the rspec-users mailing list