Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails fixtures with multiple databases

I'm trying to add test fixtures to a rails (v 3.1.3) app that uses multiple databases. The fixture should be applied only to the applications own test sqlite database:

test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

The 2 other databases are mysql and also have test instances called %dbname%_test and are already filled with test data.

After I added the fixtures all my test fail with "ActiveRecord::StatementInvalid: Mysql::Error: Unknown column" errors as rails is trying to apply the fixture to one of the mysql databases.

Is there a way to specify which database a fixture is made for?

like image 209
Abraxas Avatar asked Nov 30 '11 13:11

Abraxas


2 Answers

Fixtures-init code (in activerecord-3.2.6/lib/active_record/fixtures.rb) has a bug: in the "initialize" method, in the "else" on line 544, @connection needs to be initialized to @model_class.connection. (Without that, @connection is simply "connection" which points to the wrong DB.)

like image 105
aqn Avatar answered Sep 18 '22 00:09

aqn


In database.yml, add a connection for each of the other databases for each environment:

other_one_test:
  adapter: mysql
  # ...

other_two_test:
  # ...

other_one_development:
  # ...

other_two_development:
  # ...

In your models that use the other databases, connect to them using

establish_connection("other_one_test")

You'll probably want to create a Base class model for each different database connection and use that for all models connecting to that database:

class OtherOneBase < ActiveRecord::Base
  establish_connection "other_one_#{Rails.env}"
end

class SomeModel < OtherOneBase
end

If you set up your models correctly, your fixtures will use the correct database.

like image 40
tee Avatar answered Sep 21 '22 00:09

tee