I'm having trouble setting up the tests with fixtures that use foreign keys! And I would be much appreciated if someone could help me understand this.
Let's say for example the :user_type
model has a reference to the :role
model, when tests get executed, and all the data in the test db is deleted to be again re-inserted, Rails deletes the data from the role model first, instead of deleting the data first from the :user_type
and only then from :role
.
The fixtures:
#roles.yml
technical:
name: 'Technical'
obs: 'User Role for technical / maintenance users!'
#user_types.yml
technic:
role: technical
name: 'Technic'
is_admin: true
The tests:
#app/test/models/role_test.rb
require 'test_helper'
class RoleTest < ActiveSupport::TestCase
fixtures :roles
test 'save Role without name' do
data = Role.new()
data.valid?
assert data.errors.added?(:name, :blank), 'Role saved without name!'
end
end
#app/test/models/user_type_test.rb
require 'test_helper'
class UserTypeTest < ActiveSupport::TestCase
fixtures :user_types
test 'save User Type without role_id' do
data = UserType.new(:name => 'public')
data.valid?
assert data.errors.added?(:role_id, :blank), 'User Type saved without role'
end
end
When the tests ran for the first time, everything goes ok. Rails cleans the database (in this point is still empty, so there is no constraint violations), then the data from the fixtures gets inserted, and the tests run fine. The next time I try to run the tests they will fail because when rails starts to delete the data from the database, it starts with the role model/table instead of the user_type! Because foreign keys where defined on these models a violation will occur because user_type is still referring to data in the model table!
How should this be done properly? Is there any mechanism to tell rails the order to destroy the fixture data? I am using RubyOnRails 4 and Firebird 2.5 by the way.
I have been struggling with this for a few days and I haven’t been able to do it right!
Thank you in advance!