Postgres + tsearch2, migrations, and unit testing

I’m sure people have encountered this before, but I’ve been
unsuccessful at finding anything about it.

Basically, I got a rails app that uses postgres and tsearch2 for some
full text indexing and I’d like to be performing unit tests. Now,
there’s the whole deal of how to get the test database to load all the
tsearch2 information properly.

I tried to come up with an elegant way to do it without overwriting
any rails code or duplicating SQL or anything ugly, but didn’t manage
to. The best I came up with is as follows:

  1. In the migrations, perform all the tsearch2 related stuff for the
    table that requires full text indexing. This includes loading
    tsearch2.sql (and uninstall_tsearch2.sql in the down part), creating
    the tsvector column, the index on it, and the trigger that updates the
    tsvector column.

  2. config.active_record.schema_format = :sql in the environment since
    schemas would puke at the tsvector column.

  3. Copy all the inserts from the tsearch2.sql file and add it to a
    separate file. Setting schema_format to sql will only have the table
    structure copied to the test database, not the actual content of the
    pg_* tables which is needed to configure tsearch2. I put this in
    test/fixtures.

  4. Overwrite the db:test:prepare task with the following:

desc ‘Prepare the test database and load the schema’
task :prepare => :environment do
if defined?(ActiveRecord::Base) &&
!ActiveRecord::Base.configurations.blank?
Rake::Task[{ :sql => “db:test:clone_structure”, :ruby =>
“db:test:clone” }[ActiveRecord::Base.schema_format]].invoke
end
ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations[‘test’])
ActiveRecord::Base.connection.execute File.read(
File.join(RAILS_ROOT, ‘test’, ‘fixtures’, ‘tsearch2.sql’) )
end

Which is basically a copy of the original with the two extra lines at
the end that populate the configuration tables.

And that all seems to work. My question would be this: is there a
better way to do it? All this doesn’t seem to be too elegant.


EPA Rating: 3000 Lines of Code / Gallon (of coffee)

Well, in case anybody cares (or anybody searches for this later), I
managed to clean up the code a bit more by perparing the test database
from migrations. I took a bit of code from the code snippets site and
tweaked it to suit my needs a bit more (see my comment).