【发布时间】:2018-03-02 17:05:21
【问题描述】:
我有一个这样的关系模型:
class Physician < ApplicationRecord
has_many :appointments
has_many :patients, through: :appointments
end
class Appointment < ApplicationRecord
belongs_to :physician
belongs_to :patient
end
class Patient < ApplicationRecord
has_many :appointments
has_many :physicians, through: :appointments
end
我需要创建一个有很多患者的医师,对吗? 等等我的测试:
let!(:physician) { create(:physician) }
let!(:patients) { create_list(:patients, 2) }
我这样做了:
before { physician.patients << patients }
我想用这个测试生成的json
expect(physician.as_json).to eq({
"id" => physician.id,
"name" => physician.name,
"patients" => physician.patients
})
我期待它会通过,但因为这个#<ActiveRecord::Associations::CollectionProxy>而失败了
我使用 binding.pry 进行了检查:
physician.patients == patients
结果是true
您介意帮助我吗,我是不是遗漏了什么?
【问题讨论】:
-
physician.patients是记录的集合。它不等于预期的 json 数据。有多种写法,但基本上你的测试是错误的——你需要以某种方式定义预期结果应该是的 json 格式。 -
#as_json尽管名称返回一个可序列化的散列 - 而不是 JSON。否则你的评论会出现在@TomLord -
谢谢你@TomLord 我能够用你所有的 cmets 解决我的问题。
-
以及 @max 用于阐述和澄清 Tom Lord 的评论。我相信我想出的解决方案来自你们的 cmets
标签: ruby-on-rails ruby activerecord rspec associations