gpt4 book ai didi

ruby-on-rails - 与 Rails Fixtures 没有关联......如何修复?

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

我有一个使用 rspec/fixtures 的 Rails 5.1 项目,我无法让 fixture 加载与 belongs_to/has_one/has_many 关联的对象:我请求 fixture 的对象返回时其 _id 列填充了看似随机的number 和 ActiveRecord 将关联视为 nil。这发生在具有许多关联的大类以及只有几个字段的小数据类上。

如果在我的测试代码中,我将这些关联分配给正常的 Ruby 代码,对象将正常运行并且我的测试通过。但是,当通过固定装置加载相同的数据时,关联的记录不可用,并且需要跨越关联的数据的测试失败。

例如,这里有两个受影响的类:

#app/models/location.rb
class Location < ActiveRecord::Base
has_many :orders
has_many :end_user
belongs_to :retailer
belongs_to :depot
end

#app/models/retailer.rb
class Retailer < ActiveRecord::Base
has_many :locations
end

下面是两个对应的 fixtures 文件:

#spec/fixtures/locations.yml
loc_paris:
retailer: ret_europe (Retailer)
name: "Paris"
nickname: "paris"

loc_washington:
retailer: ret_usa (Retailer)
name: "Washington"
nickname: "washington"

#spec/fixtures/retailers.yml
ret_europe:
name: "AcmeCo France"
nickname: "acmecofr"
currency_type: "EUR"

ret_usa:
name: "AcmeCo USA"
nickname: "acmecousa"
currency_type: "USD"

使用上述数据,运行 pp locations(:loc_paris) 结果:

#<Location:0x0000000006eee1d8
id: 35456173,
name: "Paris",
nickname: "paris",
retailer_id: 399879241,
created_at: Wed, 23 May 2018 22:39:56 UTC +00:00,
updated_at: Wed, 23 May 2018 22:39:56 UTC +00:00>

这些 id 号在多次调用中是一致的,至少在相同的 RSpec 上下文中是这样。 (我将 pp locations(:loc_paris) 放在 let block 中。)但是 pp locations(:loc_paris).retailer 返回 nil

我尝试使用 FactoryBot,但我们不得不放弃它。我试图给 fixtures 一个诚实的摇晃,但似乎我们最好在实际测试代码中简单地构建数据对象......因为该解决方案没有提示:/

我是不是做错了什么?我们是否对固定装置要求过高?

谢谢!

汤姆

最佳答案

固定装置问题

看看你做了什么,locations(:loc_paris)将找到 locations.yml 中描述的记录,但是 locations(:loc_paris).retailer不会的。

Rails Associations 是这样工作的:

locations(:loc_paris).retailer将寻找 retailerretailer_idlocations(:loc_paris) 中提到记录。在你的情况下 retailer_id: 399879241并且没有 reseller有了这个id这就是它返回 Nil 的原因.

解决方案:像这样描述固定装置:

#spec/fixtures/locations.yml
loc_paris:
retailer_id: 1
name: "Paris"
nickname: "paris"

loc_washington:
retailer_id: 2
name: "Washington"
nickname: "washington"

#spec/fixtures/retailers.yml
ret_europe:
id: 1
name: "AcmeCo France"
nickname: "acmecofr"
currency_type: "EUR"

ret_usa:
id: 2
name: "AcmeCo USA"
nickname: "acmecousa"
currency_type: "USD"

现在,locations(:loc_paris).retailer将寻找 retailer_id 的零售商在 locations(:loc_paris) 中提到记录即retailer_id: 1并且有一个经销商ret_europe有了这个id . 问题已解决

当你运行 rspec 时,首先 rspec使用一些自动生成的 id 将这些固定装置保存到您的数据库中值(如果未明确提供 id),这就是 id 的原因和 reseller_id是一些随机值。如果你不想要 idlocations.yml record 是一些随机值,你可以像这样自己提供:

loc_paris:
id: 1
retailer_id: 1
name: "Paris"
nickname: "paris"

提示:作为rspectest 中运行环境(在 app/spec/rails_helper.rb 中提到),正如我之前提到的,只要你运行 rspec , 首先它将灯具保存到您的数据库中。如果你的localtest数据库相同,固定装置将替换数据库的实际数据库记录。在您的情况下,记录在 locations 中和 resellers表记录将被完全删除并替换为这些固定装置。因此,为 test 创建不同的数据库环境。

希望这个回答对您有帮助

关于ruby-on-rails - 与 Rails Fixtures 没有关联......如何修复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50498543/

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