what's the practical difference between these two FactoryGirl declarations

自作多情 提交于 2020-01-25 08:42:27

问题


I figured out this bug that took me way too long to track down.

I had this:

FactoryGirl.define do
  factory :global_list do
    list_id FactoryGirl.create(:user).liked_items_list.id
  end
end

but just wrapped in a block:

FactoryGirl.define do
  factory :global_list do
    list_id { FactoryGirl.create(:user).liked_items_list.id }
  end
end

So I know that in the second call, the block causes it to not run until an actual call like FactoryGirl.create(:global_list) is made; I assume this is getting passed and coverted to a proc via FG. Are there any other practical differences? I wish there was a way to run these in verbose mode or something.

thx for any insights


回答1:


The essential difference between the two cases is:

  1. In the first case (no block) the list_id expression is evaluated when the factory is loaded, and never again. The list_id generated on loading the factory will be used for all objects created by the factory. So all the global_list objects will have the same list_id.

  2. In the second case (with block) the list_id expression is evaluated whenever the factory is invoked (e.g. you call build(:global_list), create(:global_list)). If the list_id resulting from the expression changes, then the different factory objects will have different list_ids.



来源:https://stackoverflow.com/questions/19371480/whats-the-practical-difference-between-these-two-factorygirl-declarations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!