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