Mark
Mark

Reputation: 6455

Factory Girl - creating associated records

I've done my best to follow the documentation and similar questions on this site with no joy. I'm trying to create a ceremony, which has many invites:

ceremony.rb

class Ceremony < ApplicationRecord
  has_many :invites, dependent: :destroy
end

invite.rb

class Invite < ApplicationRecord
  belongs_to :ceremony
end

In my spec I"m trying to create invites related to a ceremony as follows:

  let(:ceremony) { FactoryGirl.create(:ceremony) }
  let(:nom_1) { FactoryGirl.create(:nominee, award: award) }
  let(:inv_1) { FactoryGirl.create(:invite, email: nom_1.email, ceremony: ceremony) }
  let(:inv_2) { FactoryGirl.create(:invite, ceremony: ceremony) }
  let(:inv_3) { FactoryGirl.create(:invite, ceremony: ceremony) }
  before do
    User.delete_all
  end
  it 'should return invites not assigned a nominee' do
    binding.pry
    expect(award.available_nominees).to include(inv_2, inv_3)
  end

When the test hits binding.pry and I go exploring, I can see a new ceremony has been created, and 3 new invites with that ceremony's ID. When I call

ceremony.invites

I receive an empty relation. When I call

Invite.where(ceremony: ceremony.id)

I receive [inv_1, inv_2, inv_3]. When I call

inv_1.ceremony

I receive the ceremony, however again

ceremony.invites

returns an empty relation. I'm at a loss why the invites are created with the correct ceremony ID, and yet the ceremony apparently has no invites. Any help is greatly appreciated.

Upvotes: 0

Views: 704

Answers (1)

spickermann
spickermann

Reputation: 106882

At the moment of creation of a ceremony there are no invites in the database. Because Rails caches database queries the invites array will stay empty unless:

  • You add invites manually: ceremony.invites = [inv_1, ...],
  • You add the invites right when creating the ceremony (in the factory or when calling the factory) or
  • you reload the ceremony or its invites relation.

I would choose the second option and would add ceremony.reload or ceremony.invites(true) before calling the expectation.

Upvotes: 2

Related Questions