Rails RSpec with Multiple Databases

后端 未结 4 974
情书的邮戳
情书的邮戳 2021-01-28 00:05

I run a Rails app, and we\'re in the process of splitting out our signup process to a separate app. The signup app has its own separate database (for CMS and collecting prospect

4条回答
  •  南笙
    南笙 (楼主)
    2021-01-28 00:36

    We have a gem that is basically a collection of ActiveRecord models that connect to our legacy system. In our case we have all those models contained in a module from which all models related to the legacy database connects.

    module Legacy
      class Base < ActiveRecord::Base
        establish_connection :legacy
      end
    
      class User < Base
      end
    end
    

    With this setup it makes it really easy to switch out the database connection. If you really go for that automated detection you can put logic in your base class to determine which database to use:

    module Legacy
      class Base < ActiveRecord::Base
        if Rails.env == 'test'
          establish_connection :legacy_test
        else
          establish_connection :legacy
       end
    end
    

    Or simply tell your module which connection to use in your spec helper:

    # spec/spec_helper.rb    
    Legacy::Base.establish_connection(ActiveRecord::Base.configurations['legacy_test'])
    

    Personally I would recommend the second option. Of course both solutions depend on namespaced models.

    Peer

提交回复
热议问题