title: Rails 3 + rspec + postgres: How to run test suite against a database with foreign key constraints?
body: <p>I have a Rails 3 application which use PostgreSQL 9.1 as a database. We use RSpec and FactoryGirl for testing. </p>
  
  <p>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:</p>
  
  <pre><code>class User &lt; ActiveRecord::Base
     attr_accessible :name
     has_many :phones
  end
  
  class Phone &lt; ActiveRecord::Base
     attr_accessible :number, user_id
     belongs_to :user
  end
  </code></pre>
  
  <p>The schema in PostgreSQL looks some thing like this</p>
  
  <pre><code>CREATE TABLE users (id integer, name VARCHAR(20));
  CREATE TABLE phones (id integer, number VARCHAR(20), user_id integer);
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>sql = "ALTER TABLE phones ADD CONSTRAINT phones_user_id FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE RESTRICT;"
  ActiveRecord::Base.connection.execute(sql)
  </code></pre>
  
  <p>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. </p>
  
  <p>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. </p>
  
  <p>Is there a way I can run my RSpec test suite against a database which enforces foreign key constraints?</p>