gpt4 book ai didi

ruby-on-rails - 如何在创建工厂之前强制 FactoryGirl 创建父级?

转载 作者:行者123 更新时间:2023-12-01 00:33:11 25 4
gpt4 key购买 nike

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

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

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

但是我的测试套件引起了问题,特别是事件工厂。
FactoryGirl.define do
factory :event do
user
end
end

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

这意味着
create(:event)
# ActiveRecord::RecordNotSaved:
# Failed to save the record


build(:event).save

通过没有错误

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

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

最佳答案

您可以在 FactoryGirl 中编写回调:

FactoryGirl.define do
factory :event do
user

before(:create) do |event|
create(:user, event_id: event.id)
end
end
end

这是 docs link

还有一个 article on thoughtbot关于 FG 回调

关于ruby-on-rails - 如何在创建工厂之前强制 FactoryGirl 创建父级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43204440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com