Use a factory's sequence to generate unique phone numbers

霸气de小男生 提交于 2019-12-11 02:59:41

问题


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!


回答1:


Try using a lambda with a random 10 digit number:

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



回答2:


Try this:

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

  factory :user do
    phone_number
  end
end

and in order to test your validation use this in your user_spec

it { should validate_uniqueness_of(:phone_number) }



回答3:


While the random solution works, you have a small chance of not getting a unique number. I think you should leverage the FactoryGirl sequence.

We can start at, 1,000,000,000 (100-000-000) and increment up. Note: This only gives you 98,999,999,999 unqiue phone numbers, which should be sufficient. If not, you have other issues.

FactoryGirl.define do
  sequence :phone_number do |n|
    num = 1*(10**8) + n
    num.to_s
  end

  factory :user do
    phone_number
  end
end



回答4:


To complete @westonplatter answer, in order to start at 0 000 000 000, you can use String#rjust:

FactoryGirl.define do
  factory :user do
    sequence(:phone_number) {|n| n.to_s.rjust(10, '0') }
  end
end

Example:

> 10.times { |n| puts n.to_s.rjust(10, '0') }
0000000000
0000000001
0000000002
0000000003
0000000004
0000000005
0000000006
0000000007
0000000008
0000000009


来源:https://stackoverflow.com/questions/18794711/use-a-factorys-sequence-to-generate-unique-phone-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!