Ruby Rails 个固定装置未加载关系

Ruby on Rails fixtures not loading relations

我有两个模型,EventRegistration:

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

我也有这些型号的固定装置:

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

但是,在测试中,如果我获取事件并检查其注册,则有 none。

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

如何确保为测试加载这些关联?

我做了一个简单的代码示例并尝试解决问题,我在查看事件和注册条目时发现的第一个想法是创建的注册 event_ids 在您的数据库中不存在。

解决方案:

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

调试器:

(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">]>

我认为这不是更好的解决方案,但可行。