gpt4 book ai didi

ruby-on-rails - Minitest:相关 AR 模型的固定装置在运行测试时导致 ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation

转载 作者:数据小太阳 更新时间:2023-10-29 07:47:43 25 4
gpt4 key购买 nike

我遇到了 Minitest 和关联 ActiveRecord 模型 (Rails.4.2.3) 的问题。

这是两个模型:

# vanguard_fund.rb
class VanguardFund < ActiveRecord::Base
belongs_to :benchmark_fund
...
end

# benchmark_fund.rb
class BenchmarkFund < ActiveRecord::Base
has_many :vanguard_funds
end

非常简单。现在这里是固定装置:

# vanguard_funds.yml
vf1:
name: Vanguard Fund 1
benchmark_fund: bm1

# benchmark_funds.yml
bm1:
name: Benchmark Fund 1

现在我在运行任何测试时遇到以下错误:

ERROR["test_#name_returns_the_name_of_the_VanguardFund", BaseTest, 2015-06-08 13:39:28 +0000]
test_#name_returns_the_name_of_the_VanguardFund#BaseTest (1433770768.22s)
ActiveRecord::InvalidForeignKey: ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: insert or update on table "vanguard_funds" violates foreign key constraint "fk_rails_994ab6fe75"
DETAIL: Key (benchmark_fund_id)=(479852872) is not present in table "benchmark_funds".
: INSERT INTO "vanguard_funds" ("name", "created_at", "updated_at", "id", "benchmark_fund_id") VALUES ('Vanguard Fund 1', '2015-09-04 16:48:23', '2015-09-04 16:48:23', 263706224, 479852872)
test_after_commit (0.4.1) lib/test_after_commit.rb:15:in `block in transaction_with_transactional_fixtures'
test_after_commit (0.4.1) lib/test_after_commit.rb:9:in `transaction_with_transactional_fixtures'

基准基金 ID (479852872),但创建 VanguardFund 时似乎在 BenchmarkFunds 表中找不到该记录??

有什么建议吗?

最佳答案

我相信 Rails 会尝试在加载固定装置之前禁用引用完整性检查。如果您的 PostgreSQL 用户不是 super 用户,那么这将无声地失败,随后 fixture 加载将失败并出现您看到的 ActiveRecord::InvalidForeignKey 错误。

修复方法是让您的 PostgreSQL 用户成为 super 用户。使用特权帐户连接到 PostgreSQL,然后发出 ALTER USER ... WITH SUPERUSER 命令。

在 Ubuntu 上,我是这样做的:

su -l postgres -c "psql -c 'alter user jenkins with superuser;'"

在这种情况下,jenkins 是未能运行 Rails 测试的用户。这解决了我的问题。

edge version of the Rails testing guide 中有对此的解释(强调):

In order to remove existing data from the database, Rails tries to disable referential integrity triggers (like foreign keys and check constraints). If you are getting annoying permission errors on running tests, make sure the database user has privilege to disable these triggers in testing environment. (In PostgreSQL, only superusers can disable all triggers. Read more about PostgreSQL permissions here).

关于ruby-on-rails - Minitest:相关 AR 模型的固定装置在运行测试时导致 ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32403150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com