Use FactoryGirl And Faker for easy data generation in unit testing (Part1)
To me it happens a lot so I found the FactoryGirl + Faker combination that made my life much more easy and now I can write tests in peace.
To add them just put in Gemfile:
gem "factory_girl_rails", "~> 4.0"
gem "faker"
So lets take a complex sample to explain all there is to know.
We have a User, the User belongs to a Company, User has many tasks.
Company has many irritating mandatory fields
Lets define the Company Factory:
FactoryGirl.define do
factory :company do
name {Faker::Name.name}
trp {Faker::Number.between(0,10)}
grp {Faker::Number.between(0,5)}
budget {Faker::Number.number(4)}
cpm {Faker::Number.between(1,70)}
trp_price {Faker::Number.between(100,700)}
viewer {Faker::Number.between(0,100000)}
total_viewer {Faker::Number.between(0,200000)}
unique_viewer {Faker::Number.between(0,50000)}
spots {Faker::Number.between(0,1000)}
end
end
As you can see I define lots of fields with random values.
Now we can create a company by writing
create(:company)Or just build one (without save to db) by calling
build(:company)
That's all for now, I'll continue in part2.
Comments