Generating sample data on Rails | BlueDiapente - Lilibeth De La Cruz


Generating sample data on Rails

I'm working on this for which I've been implementing a search functionality. Now, search is kinda difficult to test on your development machine with only a couple of records you entered manually. You need some data to actually search through it. This is also necessary if you have to present the product to somebody and need to quickly fill your database with some real looking data.

I thought it would be great if there was a gem that would allow me to enter some test data for models and generate realistic looking name and overall data for my models. I was already thinking about the API and how I would go about it when I thought that this problem is way too basic and somebody must have done it already. Like most things in the wonderful Ruby community it was already done and open sourced on GitHub.

I found not one, but a couple of sources. One of them was Forgery and the other Faker and it's supposed faster sibling FFaker (which at first I though stood for Faster Faker, but doesn't). Both seem to do pretty much the same at least on the surface. At first I was more attracted to Forgery because the home page GitHub documentation is more detailed and offers more guidance as to how to actually use it. I ended up going with Faker because it had a link in the wiki to a blog post by Michael Hutchinson with a gist for a rake task to do exactly what I wanted to do and I thought that it would save me some time with what I was doing.

I had to make some changes to the gist to get it to work for me. Of course, you need to enter your actual model and create the builders, but it was a little more than that.

  • I'm using refinerycms and the first issue I found was that my models are within modules and their full name might be something like this ::Refinery::Accounts::Account instead of simply Account and the script looks for a builder method called build_account_, build + underscore + the name of the model. This didn't work for me since I my model has colons that are not allowed as ruby methods. I got the error that the build_::refinery::accounts::account method was not found. I had to change the build method finder to instead look for a method that looked more like build__refinery_accounts_account. I also did a minor refactor so that this is done in a method and a single place instead of in the 3 places I had to go change it.

  • It seems to have been written for an older version of Rails than the one I'm using (Rails 3.2.3). It was trying to use RAILS_ENV, that has since been deprecated and replaced by Rails.env, to get the environment name in order to print a message saying the database that was going to be affected.

Overall I just had to make tiny changes and the script was of great help and saved me a lot of time (Thanks Michael!). I(as many have before me) forked it and added my changes as a Gist to GitHub mostly so that I can keep track of them.