How can I create unique strings (without numbers) with a factory girl?

Or is it an external stone needed to generate random and unique usernames?

Here is my current factory:

factory :user_4 do sequence(:id) { |n| n } sequence(:first_name) { |n| "Gemini" + n.to_s } sequence(:last_name) { |n| "Pollux" + n.to_s } sequence(:profile_name) { |n| "GeminiPollux" + n.to_s } sequence(:email) { |n| "geminipollus" + n.to_s + "@hotmail.co.uk" } end 

Using the sequence method works for id, profile_name and email, but my REGEX checks mean that the first name and surname are automatically invalid because they have a digit in them. Nothing to do with uniqueness.

So how do I create these unique names?

+8
ruby ruby-on-rails factory-bot
source share
3 answers

There are endless possible solutions for generating a random string without relying on third-party gems.

Here alone

 ('a'..'z').to_a.shuffle.join # => "sugrjtyoiqlbxkzcfnawdhpevm" 

Example

 factory :user_4 do sequence(:id) { |n| n } first_name { "Gemini" + random_name } # ... end def random_name ('a'..'z').to_a.shuffle.join end 

If the random ratio is too low, you can increase the difficulty.

+14
source share
 factory :user_4 do # ... sequence(:first_name, 'a') { |n| "Gemini" + n } sequence(:last_name, 'a') { |n| "Pollux" + n } # ... end 

The FactoryGirl #sequence method takes the second argument as its initial value. It could be String, Fixnum, or something else that supports incrementing using the #next method.

With the starting value of 'a' sequence will be a, b, c ... z, aa, ab, ac ...

+9
source share
 factory :user_4 do letters = [a,b,c,d] sequence(:id) { |n| n } sequence(:first_name) { |n| "Gemini" + letters[n] } sequence(:last_name) { |n| "Pollux" + letters[n] } sequence(:profile_name) { |n| "GeminiPollux" + letters[n] } sequence(:email) { |n| "geminipollus" + letters[n] + "@hotmail.co.uk" } end 

Or just use ascii transform or use stone faker

+2
source share

All Articles