Pregunta

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!

¿Fue útil?

Solución

Try using a lambda with a random 10 digit number:

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

Otros consejos

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) }

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

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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top