如何在创建工厂之前强制 FactoryGirl 创建父级?

And*_*vey 5 ruby-on-rails factory-bot

我有一个事件模型,当保存时,它会更新父用户的一些属性。

class User
  has_many :events
end

class Event
  belongs_to :user
  before_save :update_user_attributes

  validates :user, presence: true

  def update_user_attributes
    self.user.update_attributes(hash_of_params)
  end
end
Run Code Online (Sandbox Code Playgroud)

这在大多数情况下都可以正常工作 - 用户必须存在并登录才能与事件交互。

但是我的测试套件引起了问题,特别是事件工厂。

FactoryGirl.define do
  factory :event do
    user
  end
end
Run Code Online (Sandbox Code Playgroud)

看起来,由于 FactoryGirl 构建事件的顺序,创建事件时用户不可用,导致update_user_attributes失败。

这意味着

create(:event)
# ActiveRecord::RecordNotSaved:
# Failed to save the record
Run Code Online (Sandbox Code Playgroud)

build(:event).save
Run Code Online (Sandbox Code Playgroud)

通过没有错误

有多种方法可以防止引发错误,例如,user.persisted?update_user_attributes方法中检查该错误,或运行回调after_save。但我的问题特别与 FactoryGirl 有关。

鉴于上述事实,有没有办法在创建事件之前强制创建关联的用户?

Mar*_*sky 9

您可以在 FactoryGirl 中编写回调:

FactoryGirl.define do
  factory :event do
    user

    before(:create) do |event|
      create(:user, event_id: event.id)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

这是文档链接

还有一篇关于thoughtbot关于FG回调的文章

  • @AndyHarvey,`before(:create) do |event| event.user = create(:user) end` 我想 (5认同)