Saturday, November 23, 2013

Using Fabrication and Faker to generate test objects

Assigning text or value to a test object is quite often a tedious thing. Nevertheless, it has been an auto-generator to do this: 'Fabrication' and 'Faker'.

Fabrication (GitHub site) is a simple and powerful object generation library. Just define Fabricators, the schematics for your objects, it fabricates objects quickly as needed. Faker library that generates fake data. By combining these two gems, an automatic test object generator is ready to go for the rspec test.

Installation: Just add the following two lines to Gemfile and run bundle install to install the gems.
gem 'fabrication'
gem 'faker'
Just create the fabricator file for the Video Model object as:
spec/fabricator/video_fabricator.rb
Add the following lines to generate the two attributes of Video object:
Fabricator(:video) do
  title { Faker::Lorem.words(5).join(" ") }
  description { Faker::Lorem.paragraph(2) }
end
And it's ready to go!

In model/video_spec.rb, you have to create a Video object using:
Video.create(title: "Bones", description: "Great movie!")
When using 'Fabrication' and 'Faker' gem, all you have to do is:
let(:video)      { Fabricate(:video) }
And that is it!

No comments:

Post a Comment