ruby-on-rails - 为什么一旦做出断言(在 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 :
完全莫名其妙。你能帮我完成这个导轨升级吗?这是我最后一次失败的测试。
更新:
删除subject
getter 方法RoleChange
使测试通过,但随后我失去了从查询中包含已删除用户的好处。所以......实际上似乎不是一个解决方案。
解决方案
推荐阅读
- c - 使用 qsort 函数对结构进行排序
- arangodb - ArangoDB 通配符搜索很慢
- node.js - 如果加载 Typeorm 后满足条件,则返回空对象
- sql - 唯一的约束/引用postgres中另一个表的列
- reactjs - React Apollo 查询依赖于其他查询
- python - 如何在 Python 中找到最适合二维直方图的线?
- google-play - 仅当从 Google Play 商店安装应用程序时,cordova admob 才会出现“无填充”错误
- algorithm - 如何以后序方式创建 BST - 算法理论
- google-app-engine - GitHub在谷歌云中自动部署节点js应用
- css - 如何使 div 采用全屏尺寸并阻止其缩小