测试时按特定顺序加载Rails夹具 [英] Loading Rails Fixtures in a Specific Order when Testing
问题描述
在运行测试时,是否可以按特定顺序加载Rails灯具?例如,参加以下课程...
Is there a way to load Rails fixtures in a specific order while running tests? For example, take the following classes...
class User < ActiveRecord::Base
has_many :memberships
has_many :groups, through: :memberships
end
class Group < ActiveRecord::Base
has_many :memberships
has_many :users, through: :memberships
end
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :group
end
Memberships
具有 数据库级别 外键约束,要求在创建Users
和Groups
之前先存在它们.但是,由于Rails按字母顺序加载夹具,因此Memberships
在Users
之前加载,并且会发生错误,指出该关系不存在(正确地如此).
Memberships
have a database level foreign key constraint requiring Users
and Groups
to be present before they can be created. However, because Rails loads fixture alphabetically, Memberships
are loaded before Users
, and an error occurs stating the relationships do not exist (rightly so).
ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: insert or update on table "memberships" violates foreign key constraint
在运行测试时,是否可以在加载Memberships
之前先加载Users
和Groups
灯具?
Is there a way to load the Users
and Groups
fixtures before loading Memberships
while running tests?
推荐答案
您的问题不是Rails运行测试的顺序.我遇到了与您相同的问题,经过几个小时的调试,我意识到ActiveRecord实际上确实在插入固定记录期间禁用了参照完整性,以防止Postgresql出现此类错误.
Your problem isn't the order that Rails is running your tests. I had the same issue as you, and after debugging for a few hours realized that ActiveRecord actually DOES disable referential integrity during insertion of fixture records to prevent these types of errors for Postgresql.
要注意的是,您的测试数据库用户必须在测试数据库上具有ActiveRecord的超级用户权限,才能成功禁用Fixture所需的参照完整性.
The catch is that your test database user must have superuser privileges on the test db for ActiveRecord to successfully disable referential integrity as needed for fixtures.
这是解决问题的方法:
- 使用默认的超级用户(我的名字是"postgres")登录Postgresql
-
执行以下命令:
- Log into Postgresql with your default superuser (mine is "postgres")
Perform the following command:
ALTER ROLE yourtestdbuser WITH SUPERUSER;
享受工作正常的灯具.
Enjoy your properly working fixtures.
当一个人正在使用Postgresql运行一个测试数据库并且一个没有超级用户角色的用户运行时,Rails的下一发行版将发出警告(我认为这是非常需要的).我在 a Rails GitHub问题上提示警告.
The next release of Rails will have a warning (which I think is much needed) when a person is running a test database with Postgresql and a user without a superuser role. I found this on a Rails GitHub issue suggesting the warning.
这篇关于测试时按特定顺序加载Rails夹具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!