【问题标题】:How to create or specify associations in RSpec (rails)?如何在 RSpec (rails) 中创建或指定关联?
【发布时间】:2021-09-14 00:59:00
【问题描述】:

有两种型号: 学生科目

通过这些关联:

class Student < ApplicationRecord
  has_many :subjects
end

class Subjects < ApplicationRecord
  belongs_to :student
end

controllers 中,我可以输入以下内容以获取 id=1 的 student 正在学习的科目:

subjects = Student.find(1).subjects

问题:我如何在 RSpec 中对工厂做同样的事情?

在我的测试中,我有以下几点:

let(:student) { create(:student) }
let(:subjects) { create_list(:subject, rand(10), student: student) }

但是,执行以下操作会产生空集合:

student.subjects

【问题讨论】:

  • 也许 rand(10) 返回零

标签: ruby-on-rails rspec model associations factories


【解决方案1】:

所以我要回答我自己的问题。

很简单:

student.subjects &lt;&lt; subjects

student.subjects .class 现在将是 Subject::ActiveRecord_Associations_CollectionProxy

reference

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多