I have a Rails 3 application which use PostgreSQL 9.1 as a database. We use RSpec and FactoryGirl for testing.
The data model has lots of models in 1-to-many or many-to-many relationships, and those constraints are encoded in the Rails models using has_many, belongs_to, has_many :through, et cetera. We have code which looks something like:
class User < ActiveRecord::Base
attr_accessible :name
has_many :phones
end
class Phone < ActiveRecord::Base
attr_accessible :number, user_id
belongs_to :user
end
The schema in PostgreSQL looks some thing like this
CREATE TABLE users (id integer, name VARCHAR(20));
CREATE TABLE phones (id integer, number VARCHAR(20), user_id integer);
However, I prefer to encode the data constraints in the database using foreign key constraints instead of only in the model. To do this, I created a Rails migration and added the foreign key constraints doing something like:
sql = "ALTER TABLE phones ADD CONSTRAINT phones_user_id FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE RESTRICT;"
ActiveRecord::Base.connection.execute(sql)
When I added foreign key constraints, and started the application in development mode, the database enforced the constraints, and I wasn't able to delete a user if it had any dependent phones. And this held true whether I was in the "psql" PostgreSQL console or the IRB Rails console.
However, when I tried writing a RSpec test to see if the foreign key was enforcing delete restrictions, the test failed and I was able to delete a user with dependent phones. Apparently, "rake db:test:prepare" does not prepare databases with foreign keys.
Is there a way I can run my RSpec test suite against a database which enforces foreign key constraints?