← Back to Upcase

FactoryGirl - how to get the value of a block in an after(:create) callback


(Jonathan twaddell) #1

I have the feeling I’m not getting this at tall so I created this SO question http://stackoverflow.com/questions/19103397/how-to-get-value-of-evaluator-in-a-factorygirl-factory but this might be a bit of a tricky one to figure out. Using it right now for both seeding and testing.

Any help (answered on SO) would be appreciated. Or even better - a more elegant solution.

thx

-jt


(Ben Orenstein) #2

Have you looked into what factory_girl calls sequences? I think that might help you here.

Also, it looks like you’re assuming that you can run arbitrary code within factory definitions (like if which_one < 10, which is throwing your error), but that’s not the case, as you’ve discovered. :smile:. In fact, you can only execute a few things as defined by factory_girl’s DSL.


(Jonathan twaddell) #3

Hmm… yeah, kinda figured that out. Is there a way that I can get the name of the location inside a factory definition or create a helper? Or does FG just not allow that?


(Ben Orenstein) #4

@joshclayton Can you help?


(Josh Clayton) #5

@jon, attributes can refer to each other:

factory :user do
  sequence(:name) { |n| "Person #{n}" }
  email { "#{name.downcase.parameterize}@example.com" }
end

You can do the same with ignored attributes, so if name was an ignored attribute, you’d still be able to have email refer to it correctly.

In the case above, I think using a sequence is your best bet:

factory :location_asset, class: Asset do
  sequence(:asset) { |n| fixture_file_upload(Rails.root.to_s + "/db/seed-data/images/langers-deli/loc#{n}.jpg", 'image/jpg') }
end

Aside from sequencing assets, are you looking to do anything more complex like have the ability to override the sequence number? You have access to methods/attributes from within sequences:

factory :location_asset, class: Asset do
  ignore do
    custom_identifier nil
  end

  sequence(:asset) { |n| fixture_file_upload(Rails.root.to_s + "/db/seed-data/images/langers-deli/loc#{custom_identifier || n}.jpg", 'image/jpg') }
end
build(:location_asset) # uses the normal increment
build(:location_asset, custom_identifier: 'aksdgkasdg') # uses the custom identifier

Let me know if you have any more questions and I’ll try to provide guidance!


(Jonathan twaddell) #6

thx @joshclayton let me look through this and see if anything comes up. thx again