user3281384
user3281384

Reputation: 531

FactoryGirl - Retrieving the build strategy from an evaluator

According to the FactoryGirl documentation:

after(:build) - called after a factory is built (via FactoryGirl.build, FactoryGirl.create)

In my code, I want the callback logic to differ depending on the build strategy (known as strategy_name to FactoryGirl).

Some pseudo code:

after(:build) do |o, evaluator|
  if evaluator.???.strategy_name == 'create'
    # logic
  elsif evaluator.???.strategy_name == 'build'
    # other logic
  end
end

Does anyone know how I can leverage evaluator in the callback to get strategy_name?

Upvotes: 3

Views: 419

Answers (1)

ajjahn
ajjahn

Reputation: 192

After digging into the FactoryGirl source I wasn't able to find a supported way of doing this. I ended up opening up the Evaluator class and adding some predicate methods. Add the following to your spec_helper, test_helper or a support file.

module FactoryGirl
  class Evaluator
    def strategy_create?
      @build_strategy.class == Strategy::Create
    end

    def strategy_build?
      @build_strategy.class == Strategy::Build
    end

    def strategy_attributes_for?
      @build_strategy.class == Strategy::AttributesFor
    end

    def strategy_stub?
      @build_strategy.class == Strategy::Stub
    end

    def strategy_null?
      @build_strategy.class == Strategy::Null
    end
  end
end

In your factory:

after(:build) do |o, evaluator|
  if evaluator.strategy_create?
    # logic
  elsif evaluator.strategy_build?
    # other logic
  end
end

I'm using FactoryGirl 4.4.0. It looks like this will work with >= 3.0.0, but your mileage may vary.

Upvotes: 1

Related Questions