首页 > 解决方案 > 为什么一旦做出断言(在 rails 5.1 > 5.2 升级之后)这个模型的关联就从测试中消失了?

问题描述

我在这个应用程序中有一个跟踪角色变化的模型。我将要描述的测试在过去几年一直通过,没有问题,只是在我将 rails 版本从 5.1 升级到 5.2 时才开始失败。

以下是该模型的摘录:

class RoleChange < ApplicationRecord
  acts_as_paranoid
  belongs_to :actor, class_name: 'User', foreign_key: 'actor_id'
  belongs_to :subject, class_name: 'User', foreign_key: 'subject_id'
  validates :subject_id, presence: true

  def subject
    User.with_deleted.find(subject_id)
  end

  ...
end

规范中失败的断言如下

require 'rails_helper'

RSpec.describe RoleChange, type: :model do
  let(:organization) { create(:organization) }
  let(:admin) { organization.users.admins.first }
  let!(:user) { create(:employee_user, organization: organization) }
  subject { create(:role_change, subject: user, actor: admin) }

  describe 'associations' do
    it { is_expected.to belong_to(:actor) }
    it { is_expected.to belong_to(:subject) }
  end

  ...

end

第二个关联断言失败并出现以下错误:

  1) RoleChange associations is expected to belong to subject required:
     Failure/Error: User.with_deleted.find(subject_id)

     ActiveRecord::RecordNotFound:
       Couldn't find User without an ID
     # ./app/models/role_change.rb:28:in `subject'

这非常令人沮丧。

当我binding.pry在一个it街区内时,主题似乎是valid?和你所期望persisted?的一样。subject_id

只有当我运行断言时,它才会subject_id神奇地变成nil.

对于其他上下文,我在 Rails 控制台中的冒险:

主题在那里!

当我运行断言时,它失败并说找不到 nil :

薛定谔的外键

完全莫名其妙。你能帮我完成这个导轨升级吗?这是我最后一次失败的测试。

更新:

删除subjectgetter 方法RoleChange使测试通过,但随后我失去了从查询中包含已删除用户的好处。所以......实际上似乎不是一个解决方案。

标签: ruby-on-railsactiverecordrspec

解决方案


推荐阅读