9

如何定义一个在我的 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

这样做根本不会调用silly_horse_name;如果将其重新定义为raise 'hey!',则不会发生任何事情。

我正在使用 FactoryGirl 2.5.2。

4

3 回答 3

4

我能找到的不污染全局命名空间的最佳解决方案是在模块中定义它。例如,

module FactoryHelpers
  extend self

  def silly_horse_name
    ...
  end
end

FactoryGirl.define do
  factory :racehorse do
    name { silly_horse_name }
  end
end

资源

于 2014-01-23T04:10:26.380 回答
1

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

于 2012-08-01T13:49:59.703 回答
1

好的,这是我的两分钱(请注意史蒂夫的回答存在细微差别):

# /spec/factory_helpers.rb:

module FactoryHelpers
  extend self

  def silly_penguin_name # who says penguins can't be silly too?!
    ...
  end
end

# /spec/factories.rb:

require 'factory_helpers'

FactoryGirl.define do

  factory :racepenguin do
    name { FactoryHelpers.silly_penguin_name }
  end

end

顺便说一句,我使用的是 FactoryGirl 4.8.0 版和 Rails 4.2.0 版。

于 2017-02-21T12:07:21.070 回答