How can I define a normal method for use in one of my FactoryGirl factories? For instance:
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
Doing it this way does not call silly_horse_name
at all; if it's redefined to raise 'hey!'
, nothing happens.
I'm using FactoryGirl 2.5.2.
Factory Bot is often used in testing Ruby on Rails applications; where it replaces Rails' built-in fixture mechanism. Rails' default setup uses a pre-populated database as test fixtures, which are global for the complete test suite.
build_stubbed is the younger, more hip sibling to build ; it instantiates and assigns attributes just like build , but that's where the similarities end.
Factory Bot is a helper for writing factories for Ruby tests. It was previously known as Factory Girl.
The best solution I could find that didn't pollute the global namespace was to define it in a module. E.g.,
module FactoryHelpers
extend self
def silly_horse_name
...
end
end
FactoryGirl.define do
factory :racehorse do
name { silly_horse_name }
end
end
Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With