如何在FactoryGirl工厂定义方法?

Nat*_*ong 9 ruby factory-bot

如何定义在FactoryGirl工厂中使用的常规方法?例如:

FactoryGirl.define do
  def silly_horse_name
   verbs = %w[brunches dribbles haggles meddles]
   nouns = %w[landmines hamlets vandals piglets]
   "#{verbs.sample} with #{nouns.sample}".titleize
  end

  factory :racehorse do
    name { silly_horse_name } # eg, "Brunches with Landmines"

    after_build do |horse, evaluator|
      puts "oh boy, I built #{silly_horse_name}!"
    end

  end
end
Run Code Online (Sandbox Code Playgroud)

这样做根本不打电话silly_horse_name; 如果重新定义raise 'hey!',没有任何反应.

我正在使用FactoryGirl 2.5.2.

Ada*_*dam 1

我的建议是在main. 因此,只需将其移动到块之外的文件顶部即可FactoryGirl.define