Ruby on rails 测试时按特定顺序加载轨道固定装置
在运行测试时,是否有方法以特定顺序加载Rails固定装置?例如,以下面的课程为例Ruby on rails 测试时按特定顺序加载轨道固定装置,ruby-on-rails,unit-testing,fixtures,Ruby On Rails,Unit Testing,Fixtures,在运行测试时,是否有方法以特定顺序加载Rails固定装置?例如,以下面的课程为例 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 en
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
在运行测试时加载
成员身份之前,是否有方法加载用户
和组
装置?您的问题不在于Rails运行测试的顺序。我和你有同样的问题,在调试了几个小时后意识到ActiveRecord实际上在插入fixture记录期间禁用了引用完整性,以防止Postgresql出现这些类型的错误
问题是,您的测试数据库用户必须在TestDB for ActiveRecord上具有超级用户权限,才能根据需要成功禁用fixture的引用完整性
以下是解决问题的方法:
使用默认超级用户登录Postgresql(我的是“postgres”)
执行以下命令:
ALTER ROLE yourtestdbuser WITH SUPERUSER;
享受你正常工作的设备
在Rails的下一个版本中,当一个人使用Postgresql运行测试数据库,而另一个用户没有超级用户角色时,会有一个警告(我认为这是非常必要的)。我是在上找到的。将PostgreSQL超级用户权限授予您的“测试”帐户可以让Rails按照它想要的方式工作。在不希望/不可行的情况下
是的,如果不支持,可以控制装置的加载和删除顺序(两者都很重要)
在test/test\u helper.rb
中:
class ActiveRecord::FixtureSet
class << self
alias :orig_create_fixtures :create_fixtures
end
def self.create_fixtures f_dir, fs_names, *args
# Delete all fixtures that have foreign keys, in an order that
# doesn't break referential integrity.
Membership.delete_all
reset_cache
# If we're adding any {user, group} fixtures, add them [a] in that
# order, [b] before adding any other fixtures which might have
# references to them.
fs_names = %w(users groups) & fs_names | fs_names
orig_create_fixtures f_dir, fs_names, *args
end
end
class ActiveRecord::FixtureSet
类至少对于Rails 5,您可以使用fixtures%w[用户组成员身份]
替换fixtures:all
。它将按该顺序插入它们。但不要忘记任何装置文件:-)是否使用命名装置?请看这里:是的,我正在使用命名的fixtures。您是否尝试设置fixtures env var?和/或在测试中使用“fixtures”命令以指定要加载的夹具?我已尝试设置FIXTURE
变量。FIXTURE或fixtures?工作正常。谢谢我在RDS postgres实例中遇到了这个问题。RDS会在混音中加入什么特别的东西吗?RDS提供的“超级用户”角色是否与普通超级用户相同?我还应该补充一点,我的Rails似乎没有按字母顺序加载固定装置,因为它加载的是VanguardFunds(它依赖于BenchmarkFunds)在BenchmarkFunds之前,长期的解决方案是明确提供设备加载的顺序。这为我解决了问题(由于某种原因,我无法在RDS中更改db用户)。非常感谢你!救了我的命,伙计!使用JDBC和Informix连接进行测试。非常感谢。
class ActiveRecord::FixtureSet
class << self
alias :orig_create_fixtures :create_fixtures
end
def self.create_fixtures f_dir, fs_names, *args
# Delete all fixtures that have foreign keys, in an order that
# doesn't break referential integrity.
Membership.delete_all
reset_cache
# If we're adding any {user, group} fixtures, add them [a] in that
# order, [b] before adding any other fixtures which might have
# references to them.
fs_names = %w(users groups) & fs_names | fs_names
orig_create_fixtures f_dir, fs_names, *args
end
end