Faker: Faker should give unique values by default

Created on 18 Oct 2019  路  4Comments  路  Source: faker-ruby/faker

Is your feature request related to a problem? Please describe.
We had mindboggling difficult to debug tests that only failed occassionally, which we discovered were occurring due to Faker occasionally giving us duplicate values.

The mistake was an easy one to make, in our factories. E.g.:

# user_factory.rb
let(:identifier) { "604778#{Faker::Number.number(digits: 4)}" }

Gave us duplicate values in some rspec test runs, leading to weird test failures.

If you're adding new objects, please describe how you would use them
Instead, all calls to Faker should work by default to provide unique values, and instead of requiring developers to explicitly request non-unique values instead. This change can be made gracefully by aliasing the unique method back to the original method call, and adding a new method like repeat to cover the original behaviour instead.

Describe alternatives you've considered
The solution to my issue was adding .unique however my point is that not having this as a default sets up developer's to shoot themselves in the foot since it appears Faker is giving them uniqueness out of the box, which they will only learn the hard way later.

Most helpful comment

Not sure to have understand why you need to use Faker in this scenario.
If you expect unique number in your factory I would propose an alternative approach.

# user_factory.rb
sequence(:identifier) {|n| "604778#{'%04d' % n}" }

All 4 comments

Not sure to have understand why you need to use Faker in this scenario.
If you expect unique number in your factory I would propose an alternative approach.

# user_factory.rb
sequence(:identifier) {|n| "604778#{'%04d' % n}" }

@micred That's a nice solution, but would fail and create a phone number too long if run more than 9999 times, no?

I think the point still stands that Faker should try to give back unique values, such as when generating values like email or name. This is a safer default than letting developers shoot themselves in the foot believing Faker values are unique.

The default behavior of generating random data with replacement makes more sense to me than raising an error when the library runs out of unique values, especially since some of the value sets are quite small (for example, Faker::Internet.user_agent has only 7 values, IIRC). If it's not intuitive enough, the section Ensuring Unique Values in the README seems to be a strong enough indicator that the values aren't unique in the first place.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

CJAdeszko picture CJAdeszko  路  6Comments

tagliala picture tagliala  路  5Comments

SylarRuby picture SylarRuby  路  3Comments

benpolinsky picture benpolinsky  路  5Comments

supiash1 picture supiash1  路  5Comments