Generate Faker Data Optionally

Skip to first unread message

Natalie Blackburn

Aug 23, 2014, 5:26:26 PM8/23/14
Hey all!

I'm writing a rake task to use Faker to fill a test database. It's a lot of names, addresses, etc. for venue locations. A lot of these are mandatory, but some are optional. I'd love to have an easy way to have Faker randomly fill or not fill any of the optional fields. Has anyone done this or have good suggestions on how to make it happen? At this point we're looking at just hard coding a few with the optional fields and that doesn't seem optimal.

Thanks for any insight!

Conrad Taylor

Aug 23, 2014, 6:33:21 PM8/23/14
Natalie, you can easily use something like the following to optionally set the optional variables:

def set_optional_variable?
  rand(1_000_000) % 2 == 0 ? true : false

some_optional_variable = set_optional_variable? ? some_faker_value : nil


Think different and code well,


Sent from my iPhone
You received this message because you are subscribed to the Google Groups "Ruby Faker" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
To post to this group, send email to
Visit this group at
For more options, visit

Dave Smylie

Aug 24, 2014, 12:31:59 AM8/24/14
Nothing built directly into faker afaik, but ... you could just create an array of the optional fields and their types - then use rand() to determine a random number of optional fields to fill, rand() again to determine which fields from the array these should be, and then use faker to actually populate these fields.


Apr 10, 2016, 11:40:10 AM4/10/16
to Ruby Faker
For example email is required and first name and last name are optional:

100.times do
  user = =
  user.first_name = Faker::Name.first_name if Faker::Boolean.boolean
  user.last_name = Faker::Name.last_name if Faker::Boolean.boolean!
Reply all
Reply to author
0 new messages