Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sequence correctly with factory_girl in rails development environment?

I want to integrate factory_girl in rails development environment for quickly creating records. However, every time I open rails console and do some actions, the sequence state always begins from zero, which leading to error of violating uniqueness. Such as:

FactoryGirl.define do
  factory :user do
    name 'Jim'
    email
  end

  sequence :email do |n| # every time n begins at 0
    "#{n}@exmaple.com"
  end
end

Do you have some simple solutions to solve this problem? Thank you!

like image 659
Run Avatar asked Oct 16 '25 04:10

Run


1 Answers

You can set the initial value of n if you wish. you can achieve this by:

FactoryGirl.define do
  factory :user do
    name 'Jim'
    sequence :email, 100 do |n|
      "#{n}@exmaple.com"
    end
  end
end

or

FactoryGirl.define do
      factory :user do
        name 'Jim'
        sequence(:email, 100) { |n| "person#{n}@example.com" }
      end
end

note: n = 100 in this case for more info check out the documentation here

like image 59
mrvncaragay Avatar answered Oct 17 '25 17:10

mrvncaragay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!