spring icon indicating copy to clipboard operation
spring copied to clipboard

Multiple databases are incompatible (since Rails/ActiveRecord 6)

Open simoleone opened this issue 4 years ago • 0 comments

Using the new built-in multiple database support seems to be incompatible with Spring.

A minimal example that can reproduce the issue is below. For the sake of example, assume there is some really boring model called Account which can be created with just an email address.

In the below minimal RSpec test...

  • Both examples FAIL when run through Spring. The failure is ActiveRecord::ReadOnlyError due to Account.create!
  • Both examples PASS when not run through Spring.
RSpec.describe 'something' do
  let!(:stuff) { Account.create!(email: '[email protected]') }

  it 'should do things' do
    ActiveRecord::Base.connected_to(role: :reading) do
      expect(Account.count).to eq(1)
    end
  end

  it 'should do other things' do
    expect(Account.count).to eq(1)
  end
end

The relevant part of ApplicationRecord

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true

  connects_to database: { writing: :primary, reading: :primary_replica }
end

Our hypothetical Account is just an empty class.

class Account < ApplicationRecord
end

And the relevant section of database.yml, which is about as default as it comes.

default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

test:
  primary: &primary
    <<: *default
    url: <%= ENV['TEST_DATABASE_URL'] %>
  primary_replica:
    replica: true
    <<: *primary

simoleone avatar Mar 23 '21 09:03 simoleone