[rspec-users] Foreign key constraints, fixtures, and rake task

Tilmann Singer tils-rspec at tils.net
Mon Aug 27 04:54:28 EDT 2007


* Jay Levitt <lists-rspec at shopwatch.org> [20070827 03:51]:
> I've got a spec that loads a fixture in the "before" block.  This works 
> fine running scripts/spec, but when I run rake spec instead, I get:
> 
> ActiveRecord::StatementInvalid in 'User in fixture :quentin with an IM 
> service but no IM name should be invalid'
> Mysql::Error: Cannot delete or update a parent row: a foreign key 
> constraint fails (`mediajoint_development/accounts`, CONSTRAINT 
> `accounts_opener_id_fk` FOREIGN KEY (`opener_id`) REFERENCES `users` 
> (`id`)): DELETE FROM users
> /Users/jay/Documents/eclipse/mediajoint/vendor/plugins/rspec_on_rails/lib/spec/rails/dsl/behaviour/model.rb:12:in 
> `before_eval'
> 
> I've even manually run the entire "ruby -I" command that rake generates, 
> and it works fine.
> 
> I can't see that the rake task's doing anything different other than 
> db:test:prepare, which I can do manually with no problem.
> 
> What's rake doing differently?

rake spec isn't doing anything fundamentally different, but the order
the specs are run is propably randomly different from when you run
them with spec so they happen to pass in one case and fail in the
other.

Using fixtures when there are foreign key constraints in the db can be
a pain - if the speed is acceptable it's propably best to do

fixtures :all

whenever you need any of the fixtures, or leave the fixtures
declaration out if a describe block doesn't need any.

I guess the error you are seeing is because a fixtures declaration is
encountered that references users fixtures, but not accounts. When
preparing the fixtures for a describe block, ActiveRecord deletes all
rows in all declared tables and then fills them with the fixtures
data. In your case it wants to delete all from users but doesn't do
anything with accounts where there are still rows from a spec that ran
previously, and those rows reference users. You could also try to add
:accounts to that particular failing spec to get rid of this one
error.


Til


More information about the rspec-users mailing list