问题
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:
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.
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