Between creating migrations, classes, and methods with Ruby, learning my first backend language has been challenging enough. When tackling the intimidating task of learning a new programming language, why waste valuable time coming up with usable data examples? Luckily, there’s a simple way of generating data in order to save time and test your model’s relationships. Using the ruby gem Faker we are able to create, as the official Github page explains, “real-looking test data” for development. From cannabis strains to 100% authentic Chuck Norris “facts,” faker has fake data for all your seeding needs.
In order to use faker you must first make sure it is in your Gemfile and properly installed.
The next step is browsing the official Faker Github and finding the random data type of your liking. For our example we’ll take a Chuck Norris “quote.”
Using the given syntax, we can now insert this data into our seed file.
Now after loading our seed data from db/seed.rb we will have 10 instances of “Fact” with the name Chuck Norris and a random fact from the faker database. One thing to note is that Faker will generate new random data every time you seed your database, so be careful.
One last important piece of information that the Faker Github provides is that the random data generated will not always be unique. If you’re trying to explicitly receive unique data from faker, you’ll need to prefix your method call with unique.