Search code examples
ruby-on-railsrspecfactory-bot

Using multiple sequence in Factory-girl


I am carrying out a test for a feature which requires a user factory. I am having a problem with defining factory with multiple sequence like this:

FactoryGirl.define do

  sequence(:username, 1, aliases: [:sender, :receiver]) { |n| "user#{n}"};
  sequence(:email, 1, aliases: [:sender, :receiver]) { |n| "user#{n}@example.com"};

  factory :user do
    username
    email
    password "secret"
    password_confirmation "secret"
    role "1"
  end

end

So far this is what i am trying to achieve but it fails with this error message - "Sequence already registered: sender (FactoryGirl::DuplicateDefinitionError)" when i run the test.

i have tried several other ways but can't seem to achieve it. It works with only one sequence but fails when i try with two. I understand the error message besides I am using factory-girl for the first time and would appreciate some clarification on how to achieve it.


Solution

  • Try this

       FactoryGirl.define do
          sequence :email do |n| 
            "email#{n}@factory.com"
          end 
    
          sequence :username do |n| 
            "testuser#{n}"
          end 
    
          factory :user do
            username
            email
            password "secret"
            password_confirmation "secret"
            role "1"
          end
    
        end