Search code examples
ruby-on-railsrspectddsequencefactories

Use a factory's sequence to generate unique phone numbers


I'm new to TDD, RSpec and factories, and trying to understand how to test that each User's phone number attribute is unique. To do so, I'm trying to use a sequence in my User factory. I'm not having much luck with the following:

FactoryGirl.define do
  factory :user do
    number = 123456789
    sequence(:phone_number) {|n| (number + n).to_s }
  end
end

Any thoughts on the best way to accomplish this? Also, what kind of test would make sense for something like this where ultimately I would want to add the following validation to the user model to make such a test pass?

validates :phone_number, :uniqueness => true

Thanks!


Solution

  • Try using a lambda with a random 10 digit number:

    phone_number { rand(10**9..10**10) }