Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define a method on a FactoryGirl factory?

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.

like image 250
Nathan Long Avatar asked Aug 01 '12 13:08

Nathan Long


People also ask

What is Factorybot used for?

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.

What is Build_stubbed?

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.

What is Factorybot in Rspec?

Factory Bot is a helper for writing factories for Ruby tests. It was previously known as Factory Girl.


1 Answers

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

like image 67
Steve Avatar answered Nov 04 '22 18:11

Steve