Generating randomized test data in Rails with Faker
Yesterday we discussed spinning up test data with FactoryBot. Today we'll expand upon that idea by using Faker, a gem with all sorts of whimsical modules for easily creating randomized data.
Faker's API
Faker has a ton of modules for generating data, all of which can be invoked with an API like Faker::Module.method
. For example, the Name
module can be used to generate, well, names of course:
> Faker::Name.first
> "Shirley"
> Faker::Name.last
> "Ernser"
Combining with FactoryBot
Let's update our user factory that we discussed yesterday to use Faker::Name
to generate random user names. Here's the factory with a hardcoded default user name:
FactoryBot.define do
factory :user do
sequence(:email) { |n| "test#{n}@example.com" }
password { "password" }
first_name { "John" }
last_name { "Dorian" }
end
end
Here's the factory leveraging Faker:
FactoryBot.define do
factory :user do
sequence(:email) { |n| "test#{n}@example.com" }
password { "password" }
first_name { Faker::Name.first_name }
last_name { Faker::Name.last_name }
end
end
Generating unique values
Have an attribute that needs to be unique? Yesterday we talked about achieving this using FactoryBot sequences (as seen above for the email
attribute), but what if we want our Faker
data to be unique?
Faker provides a unique
method that guarantees a random result (caveat: it can run out of unique results).
Faker::Name.unique.name # This will return a unique name every time it is called
More than just names
First and last names are just the beginning. Faker has a lot of modules for generating fake data.
There are modules for addresses, lorem ipsum, phone numbers, mountains, and more! Whatever you need, Faker
is likely to have you covered.
Delightful whimsy
Faker isn't all business. Are you a Tolkien fan like me? You did see the painting of The Shire behind me in my headshot, didn't you?
Faker::Movies::LordOfTheRings.character #=> "Legolas"
Faker::Movies::LordOfTheRings.location #=> "Helm's Deep"
Conclusion
That wraps up for today. I hope you give Faker
a spin and see if you enjoy working with it. Tomorrow we'll talk about a gem that adds some useful one-line tests to your arsenal for testing all sorts of things in your ActiveRecord
models.