user2775888 user2775888 - 1 year ago 91
Ruby Question

Why does this factory with initialize_with cause a FactoryGirl::SyntaxRunner error?

FactoryGirl.define do
factory :costs_estimator do
ignore do
detailed_outcome_estimate nil
finance_estimate { detailed_outcome_estimate.try(:finance_estimate) }
task_estimators do
if detailed_outcome_estimate.present?
[ build(:task_estimator) ]
end
end
end
end

initialize_with do
new(finance_estimate, task_estimators)
end
end


I built a model called costs_estimator with an initializer, and I added this above factory for it. The problem now is that when I run RSpec, other tests report an error:

factory_girl-4.2.0/lib/factory_girl/evaluator.rb:42:in `method_missing':
undefined method `finance_estimate' for #<FactoryGirl::SyntaxRunner:0x00000009c542a8>
(NoMethodError)...


Does anyone have an idea what is happening with this factory and why it affects other tests? If you need more info, let me know.

Answer Source

You probably want initialize_with to apply only to the :costs_estimator factory. If so, move it inside that definition:

FactoryGirl.define do 
  factory :costs_estimator do 
    ignore do 
      detailed_outcome_estimate nil
      finance_estimate { detailed_outcome_estimate.try(:finance_estimate) }
      task_estimators do 
        if detailed_outcome_estimate.present?
          [ build(:task_estimator) ]
        end
      end
    end

    initialize_with do 
      new(finance_estimate, task_estimators)
    end

  end    
end

factory_girl does allow you to define initialize_with at the top level, in which case it will apply to all factories, but that will definitely break factories that don't define finance_estimate and task_estimators, and it's possible that it won't even work with virtual attributes, since those are defined only in the context of a single factory.