Reset 'sequence' for FactoryGirl tests
Asked Answered
S

2

5

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.

Severson answered 28/7, 2012 at 0:36 Comment(0)
A
4

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.

Aventurine answered 16/4, 2013 at 23:1 Comment(0)
A
3

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.

Aventurine answered 6/5, 2013 at 11:57 Comment(1)
This seems to work well inside a let block as a way to create a collection of model objects (or children of a parent model) and consistently get the same results every time.Factory

© 2022 - 2024 — McMap. All rights reserved.