Reset 'sequence' for FactoryGirl tests

こ雲淡風輕ζ 提交于 2019-12-10 15:59:17

问题


Does anyone know how to reset the sequence method for FactoryGirl?

I have a factory that creates a list of tasks and I want to order to start at 1 every time. I use 'sequence' because the task list is a associated model, so I would need the order to increase every time I use FactoryGirl.create until I call a reset.


回答1:


You need to write FactoryGirl.reload in the before/after callback of the test file.

Example code snippet

  before do
    FactoryGirl.reload
    .
    .
    .
  end

The '.' represents other code.

Preferably write FactoryGirl.reload unless FactoryGirl.factories.blank? so that FactoryGirl does not reload, when it does not have to.


Doing a full reload of FactoryGirl might have some overhead on the time it takes to process the test(s); this is also what is described as Anti-Patterns.




回答2:


Instead of using FactoryGirl.reload and thus creating an Anti-Pattern effect. You could pass unique values to FactoryGirl to increment for those fields when it creates the new entries.

Example code snippet (This example code creates 5 tasks assuming the Factory is called Task)

  before do
    (1..5).each do |n|
      FactoryGirl.create(:task,
        name:       "Task_unique_test_name#{n}"
      )
    end
  end

That way the new set of tasks order starts at 1 every time and you avoid having to reload FactoryGirl.



来源:https://stackoverflow.com/questions/11697235/reset-sequence-for-factorygirl-tests

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