Faking Data - Seeding your database with mock objects

By Nick Rodriguez

When first testing a new application, it's tempting to just build whatever objects you need to test a particular feature at that moment. If you're not careful, however, your test files can quickly start looking something like this:

faking_data_bad_mock.PNG
Bad test object generation

This is bad. Don't do this.

It's slow, hard to maintain, and bulky.

Instead, with the use of the Fabrication and Faker gems, you can generate as many fake objects as you want before running your test suite. Faker is a library that generates fake data such as names, addresses, and phone numbers, and Fabrication is a Ruby object generation framework.

Add the two gems to your gemfile, then build Fabricators that mirror the models you wish to generate.

./spec/fabricators/movie_fabricator.rb
faking_data_fabricator_movie.PNG
Movie fabricator

Here our Movie is being generated with a name attribute that our test suite expects to be unique.

./spec/fabricators/user_fabricator.rb
faking_data_fabricator_user.PNG
User fabricator

Then we create a Users fabricator (aliased as Reviewer).

./spec/fabricators/review_fabricator.rb
faking_data_fabricator_review_alt.PNG
Basic review fabricator

Finally, we create a Review fabricator, which creates Reviews that belong to both a Reviewer (User) and a Movie. This configuration is fine as long as you want each movie and user to only have one review. The Fabricator object will automatically look up the respective fabricators for both Reviewer and Movie and build them as needed. If, however, you want to model multiple reviews per movie/user, you'll need to amend this file to something like the following:

./spec/fabricators/review_fabricator.rb
faking_data_fabricator_review.PNG
Better review fabricator 

Now our Review Fabricator will either pick a random User/Movie or generate new ones. So now we just need to call this fabricator from our seeds.rb file.

./db/seeds.rb
faking_data_seeds.PNG
Seeding the DB

This file is called whenever you run $ rake db:seed. 

Since your test runner should be clearing its testing DB whenever your test suite is run, if you want it to have data to work with you'll need to add your seeds.rb file to your testing config.

./spec/spec_helper.rb
faking_data_config.PNG
Ensuring that your test DB is seeded when running `rspec`

Now, whenever we run $ rspec, our seed file will be called, generating 100 new reviews, and somewhere between 1 and 100 Users and Movies for use in our test suite. Those objects will then be destroyed when our tests have completed.

Random object generation grants us two huge advantages: by testing against randomly generated objects, we can be confident that our tests are designed abstractly; and we can quickly create a lot of content to use in our front-end work.


  Creating a simple Ruby Gem from scratch|Building a CRUD application with Sinatra