Rails RSpec with Multiple Databases

后端 未结 4 948
情书的邮戳
情书的邮戳 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:50

    Here's what I came up with as a mixin:

    # lib/establish_connection_to_master_database.rb
    module EstablishConnectionToMasterDatabase
      def establish_connection_to_master_database
    
        case RAILS_ENV
        when "development"
          establish_connection :master_dev
        when "test"
          establish_connection :master_test
        when "production"
          establish_connection :master
        end
    
      end
    end
    ActiveRecord::Base.send(:extend, EstablishConnectionToMasterDatabase)
    
    # models/subscription.rb
    class Subscription < ActiveRecord::Base
      establish_connection_to_master_database
    end
    
    # config/initializers/config.rb
    require 'establish_connection_to_master_database'
    

    In order for this to work with RSpec, this needs to be loaded in an initializer - apparently loading it in the environment file causes it to be loaded it too late, and it won't work.

提交回复
热议问题