【问题标题】:How to run a method in FactoryBot?如何在 FactoryBot 中运行方法?
【发布时间】:2021-03-08 02:28:04
【问题描述】:

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

所以我试图在 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

【问题讨论】:

    标签: ruby-on-rails factory-bot


    【解决方案1】:

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

    class FactoryBot::DefinitionProxy
      def my_custom_method
        ...
      end
    end
    
    FactoryBot.define do
      factory :my_thing do
        my_custom_method
    
        label { "My Label" }
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      • 1970-01-01
      相关资源
      最近更新 更多