如何定义一个正常的方法用于我的 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。
最佳答案
我能找到的不污染全局命名空间的最佳解决方案是在模块中定义它。例如,
module FactoryHelpers
extend self
def silly_horse_name
...
end
end
FactoryGirl.define do
factory :racehorse do
name { silly_horse_name }
end
end
关于ruby - 如何在 FactoryGirl 工厂上定义方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11760704/