0

我很高兴能制作一个find_or_create_byfactorybot 工厂版本。但是,我想用一行(例如,包含语句或方法调用)将代码添加到工厂,而不是将整个块粘贴到每个工厂。

所以我试图将一个方法插入FactoryBot,但工厂只是抱怨该方法的名称不是注册的特征。如何从工厂调用方法?

class FactoryBot::Declaration::Implicit
  def change_factory_to_find_or_create
    # This hook allows us to do find_or_create for factories
    to_create do |instance|
      attributes = instance.class.find_or_create_by(instance.attributes.compact).attributes
      instance.attributes = attributes.except('id')
      instance.id = attributes['id'] # id can't be mass-assigned
      instance.instance_variable_set('@new_record', false) # marks record as persisted
    end
  end
end

FactoryBot.define do
  factory :my_thing do
    change_factory_to_find_or_create

    label { "Label One" }
  end
end
4

1 回答 1

0

答案是打开了错误的类。它应该是:

class FactoryBot::DefinitionProxy
  def my_custom_method
    ...
  end
end

FactoryBot.define do
  factory :my_thing do
    my_custom_method

    label { "My Label" }
  end
end
于 2021-03-08T23:52:20.550 回答