Multiple Postgres Schemas and Rails db:test:prepare

In our Rails databases, we use multiple Postgres schemas. This is partly for partitioning archive data from fresh data. On a new Rails 5 project, I started having tests fail once the models had the "archivable" concern added, which depended on an archive schema existing.

Ultimately, the problem is that the archive schema wasn't being created in the test database, because rake db:test:prepare performs a db:test:load which was loading the db/schema.rb, which is completely ignorant of the Postgres-specific schema concept.

In order to fix this without attempting ugly hacks, the simplest solution was just to switch to using structure.sql for the Rails schema dump.

In config/application.rb, insert the following in your Application class definition:


config.active_record.schema_format = :sql

If you haven't already added the additional schema(s) to your schema_search_path in your config/database.yml.


database: whatever_db
schema_search_path: 'main,main_archive,public'

You'll need to run rake db:migrate to force structure.sql generation before running tests again. Also, be sure to switch from schema.rb to structure.sql if you're committing this file.