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

2

6

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?

Malayan answered 16/6, 2015 at 16:28 Comment(0)
M
5

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
Malayan answered 17/6, 2015 at 9:42 Comment(0)
L
0

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

Larcenous answered 16/6, 2015 at 17:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.