How to create or specify associations in RSpec (rails)?

955 Views Asked by At

There are two models: student and subjects

With these associations:

class Student < ApplicationRecord
  has_many :subjects
end

class Subjects < ApplicationRecord
  belongs_to :student
end

In controllers, I can enter the following to get the subjects being taken by a student with id=1:

subjects = Student.find(1).subjects

Question: How do I do the same thing with factories in RSpec?

In my test, I have the following:

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

But, doing the following gives empty collection:

student.subjects
1

There are 1 best solutions below

1
threecheese On

So I’m going to answer my own question.

It’s as easy as:

student.subjects << subjects

student.subjects .class will now be Subject::ActiveRecord_Associations_CollectionProxy

reference