如何解决奇怪的 minitest 夹具关联问题
我有一个具有如下关联的模型:
belongs_to :state_user,class_name: "User",foreign_key: "state_user_id"
在固定装置中我有这个:
相关模型:
one:
state_user: administrator (User)
用户:
administrator:
name_first: 'Joe'
name_last: 'Administrator'
然而在我的测试中,这个关联失败了:
test 'should have state user' do
assert @transfer.state_user.present?
end
FAIL TransfersControllerTest#test_should_have_state_user (174.10s)
Expected false to be truthy.
test/controllers/transfers_controller_test.rb:64:in `block in <class:TransfersControllerTest>'
我以前遇到过这个问题,我的黑客就是这样做并直接通过用户 ID 引用:
one:
state_user_id: 99
# state_user: administrator (User)
fixed:
id: 99
name_first: "Mary"
name_last: "Fixed"
此测试随后通过但并不理想。此代码在开发和生产中运行良好 - 在这种特殊情况下失败。我唯一的想法是我在 belongs_to
声明中遗漏了一些东西。
更新
按照评论中的建议添加了一个错误的休息时间:
(byebug) @transfer.state_user
nil
(byebug) @transfer.state_user_id
924281465
(byebug) User.where(name_first: 'Joe')
#<User id: 417269330,name_first: "Joe",name_last: "Administrator">
我再次尝试不同的用户运行此程序 - 结果相同。这几乎就像在传输模型等中设置用户 ID 后第二次创建它们一样。
顺便说一句,我还有其他 belongs_to
用户是这样的:
belongs_to :state_user,foreign_key: "state_user_id"
# The user that created the transfer
belongs_to :initiated_user,foreign_key: "initiated_user_id"
# The user that the transfer is assigned to
belongs_to :user
# The user that approves the transfer to proceed
belongs_to :approval_user,foreign_key: "approval_user_id"
# The user that completed the transfer
belongs_to :completed_user,class_name: :user,foreign_key: "complete_user_id"
现在只有最后一个抛出这个错误:
Minitest::UnexpectedError: ActiveRecord::Fixture::FixtureError: table "transfers" has no columns named "complete_user".
所有这些 belongs_to
用户也返回了错误的用户名称。
解决方法
多么疯狂的问题?♂️
我偶然发现了这篇旧帖子:
https://brandonhilkert.com/blog/7-reasons-why-im-sticking-with-minitest-and-fixtures-in-rails/
由此我意识到我不需要在我的装置中指定 (User)
,因为它们不是多态的。删除修复了问题
one:
state_user: administrator
也是complete_user
的?♂️时刻 - 需要:
one:
state_user: administrator
completed_user: operator # NOT complete_user
希望这能帮助其他人。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。