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:
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 gemfile
Here our Movie is being generated with a name attribute that our test suite expects to be unique.
Then we create a Users fabricator (aliased as Reviewer).
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:
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 seeds.rb
This file is called whenever you $ 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 seeds.rb
Now, whenever we $ rspec
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