最小测试夹具引用了不正确的对象

问题描述 投票:0回答:1
class Document < ApplicationRecord
  
  belongs_to :individual, optional: true
  belongs_to :union, optional: true

执行测试后

patch document_url(documents(:one)), params: { document: { title: documents(:two).title } }, xhr: true
返回错误:

ActiveRecord::RecordNotFound: Couldn't find Individual with 'id'=498572325
    app/controllers/documents_controller.rb:42:in `update'

控制器搜索文档的所有者并生成实例变量

@individual = Individual.find(@document.individual_id)
。控制器中的
puts
返回与错误一致的
@document.individual_id 498572325

documents.yml 的固定装置是

one:
  title: MyString1
  synopsis: MyString1
  individual: individuals(:one)

two:
  title: MyString2
  synopsis: MyString3
  union: unions(:one)

而 individual.yml 没有建立固定 ID,留给测试环境

one:
  shop: shops(:one)
  categoryminor: categoryminors(:one)
  union: unions(:one)
  name_last: MyString1
  name_first: MyString1

在测试中,在调用更新操作之前,我们在登录用户之前验证 individual(:one).id 的值并获取

puts individuals(:one).id
==> 980190962

所以测试结果是一致的。据我所知,“个人”不是一个保留词

为什么测试数据会发生变化?

ruby-on-rails minitest
1个回答
0
投票

您面临的问题似乎与测试环境中为个人设置(或自动生成)的 ID 与尝试在更新操作中查找个人记录时引用的 ID 之间的差异有关您的documents_controller。

以下是诊断和解决问题时需要考虑的一些步骤和要点:

夹具 ID:默认情况下,Rails 会根据夹具名称和模型名称生成夹具 ID。这有助于确保 ID 在测试运行中保持一致。但是,在您的情况下, individual(:one) 的 ID 似乎是 980190962,而 @document.individual_id 是 498572325。这种差异表明您的测试或设置中可能存在一些其他操作正在修改与文档关联的个人.

数据库清理:确保您使用某种策略在测试运行之间清理测试数据库,例如database_cleaner gem。这可以确保旧数据不会干扰新的测试运行。

检查测试设置:检查测试中的任何之前的块或设置方法,以确保您不会无意中更改与文档关联的个人或创建可能干扰测试的新个人记录。

灯具中的显式 ID:确保 ID 保持一致的一种方法是在灯具中显式设置它们:

检查回调:确保模型中没有回调(例如 before_save、after_create 等),这些回调可能会以影响测试的方式更改关联或修改记录。

日志记录:在测试和控制器中添加更多日志记录。例如:

puts "Document ID: #{@document.id}"
puts "Document's individual_id: #{@document.individual_id}"
© www.soinside.com 2019 - 2024. All rights reserved.