繁体   English   中英

RSpec has_many通过# <ActiveRecord::Associations::CollectionProxy>

[英]RSpec has_many through #<ActiveRecord::Associations::CollectionProxy>

我有很多这样的直通关系模型:

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

您介意帮助我,我在这里错过了什么吗?

要链接医师和患者,只需将密钥传递给create_list

let!(:patients) { create_list(:patients, 2, physician: physician ) }

或者,您可以将其声明为:

let(:physician) { create(:physician, patients: build_list(patients: 2)) }

但是如@TomLord所述,测试本身仍未通过。 您需要测试生成的哈希-因为包含关联将导致将其转换为序列化的哈希:

{
  "id" => 1,
  "name" => "Dr Suess",
  "patients" => [
     {
        "id" => 1,
        "name" => "The Cat in The Hat"
     },
     {
        "id" => 2,
        "name" => "The Grinch"
     },
  ]
}

eq测试精确的输出不是最佳的,因为每次对序列化的更改都会破坏测试。 相反,您可以使用include匹配器来指定必须存在的内容:

describe '#as_json' do
   let!(:physician) { create(:physician) }
   let!(:patients) { create_list(:patients, 2) }
   subject(:serialized) { physician.as_json } 

   it { should include({
        "id" => physician.id,
        "name" => physician.name
   }) }
   it "includes the patients" do
      expect(serialized["patients"].length).to eq patients.length
      expect(serialized["patients"]).to include patients.first.as_json
      expect(serialized["patients"]).to include patients.last.as_json
   end
end

除非您重写了as_json方法,否则此规范应该会失败,因为您需要显式包括与as_json physician.as_json(include: :patients) as_json关联。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM