Inspired by this SO question:
I’ve had a lot of trouble recently with Rails and PostGIS. One of the main problem arised with testing. When you run Rails tests (or RSpec for that matter) the test database is always dropped and a new is created. The problem with this is, that the PostGIS extension is not created in this new database. Therefore your schema-load will fail, if you have any postgis-specific fields/indices.
The solution to this is to use a PostgreSQL database template – and of course the activerecord-postgis-adapter found here: https://github.com/dazuma/activerecord-postgis-adapter
First the template:
You need a PostgreSQL template with PostGIS functions support.
Create a template database:
$ psql -U postgres > CREATE DATABASE template_postgis WITH TEMPLATE=template1 ENCODING='UTF8'; > \c template_postgis; > CREATE LANGUAGE plpgsql;
Load necessary PostGIS functions into template (your SQL files may be located in a different path, but they come with the PostGIS installation):
$ psql -U postgres -f /usr/share/postgresql/9.1/contrib/postgis-2.1/postgis.sql template_postgis $ psql -U postgres -f /usr/share/postgresql/9.1/contrib/postgis-2.1/spatial_ref_sys.sql template_postgis $ psql -U postgres -f /usr/share/postgresql/9.1/contrib/postgis-2.1/topology.sql template_postgis
Set database as template and grant permissions:
$ psql -U postgres template_postgis > UPDATE pg_database SET datistemplate = TRUE WHERE datname = 'template_postgis'; > GRANT ALL ON geometry_columns TO PUBLIC; > GRANT ALL ON spatial_ref_sys TO PUBLIC; > GRANT ALL ON topology TO PUBLIC;
Now the adapter:
Add this gem to your Gemfile and run bundle:
After that add the adapter and the template to your config/database.yml like this:
development: adapter: postgis template: template_postgis database: mydb_development test: adapter: postgis template: template_postgis database: mydb_test
And that should do the trick! Test it by running rake db:schema:dump and rake db:test:prepare.
Let me know, if you get any additional problems regarding this.