Sequence within trait of FactoryGirl factory does not use main sequence counter

2.2k views Asked by At

I have the following factory:

FactoryGirl.define do
  factory :foo do
    sequence(:name) { |n| "Foo #{n}" }

    trait :y do
      sequence(:name) { |n| "Fooy #{n}" }
    end
  end
end

If I run

create :foo
create :foo
create :foo, :y

I get Foo 1, Foo 2, Fooy 1. But I want Foo1, Foo2, Fooy 3. How can I achieve this?

2

There are 2 answers

0
dav_i On BEST ANSWER

After a couple of hints from smile2day's answer and this answer, I came to the following solution:

FactoryGirl.define do
  sequence :base_name do |n|
    " #{n}"
  end

  factory :foo do
    name { "Foo " + generate(:base_name) }

    trait :y do
      name { "Fooy " + generate(:base_name) }
    end
  end
end
0
smile2day On

You defined two different sequence generators since they are not within the same scope.

I would not use :name for the generator. A name that implies a number seems more suitable.

sequence :seq_number

Include a transient attribute in the factory and assign the generated sequence nunber.

transient do
  seq_no { generate(:seq_number) }
end

Use the transient attribute for the 'name' attribute. The same applied to the trait version of 'name'.

name { "Foo #{seq_no}" }

trait :y do
  name { "Fooy #{seq_no}" }
end

Cheers, Eugen