Search code examples
ruby-on-railsrubytestingassociationsfixtures

Ruby on Rails fixtures not loading relations


I have two models, Event and Registration:

class Event < ApplicationRecord
  has_many :registrations
end
class Registration < ApplicationRecord
  belongs_to :event
end

I also have fixtures for these models:

event_one:
  [...]
registration_one:
  event: event_one

However, in test, if I get the event and check its registrations, there are none.

event = events(:event_one)
puts event.registrations.count # Prints: 0

How do I make sure these associations are loaded for tests?


Solution

  • I did a simple example of your code and try solve the problem, the first thinks I found when review the Event and Registration entries is that the Registrations created has event_ids that dont exist in your database.

    A solution:

    events.yml

    event_one:
      id: 111
      name: MyString
      description: MyString
    

    registrations.yml

    registration_one:
      name: MyString
      event_id: 111
    
    registration_two:
      name: MyString
      event_id: 111
    

    event_test.rb

    require 'test_helper'
    
    class EventTest < ActiveSupport::TestCase
      def setup
        @event = events(:event_one)
      end
    
      test "the truth" do
        byebug
      end
    end
    

    debugger:

    (byebug) @event.registrations
    #<ActiveRecord::Associations::CollectionProxy [#<Registration id: 357093202, name: "MyString", event_id: 111, created_at: "2021-01-09 17:21:48", updated_at: "2021-01-09 17:21:48">, #<Registration id: 1055835082, name: "MyString", event_id: 111, created_at: "2021-01-09 17:21:48", updated_at: "2021-01-09 17:21:48">]>
    

    I don't think this is the better solution but work.