Using faker to test your application

Recently I needed some data to test such features as pagination and search. I only had 10 fixtures in the database and this wasn’t enough to test on.

I could have created a bunch of records filling in the fields with random characters but that is a not a very eloquent solution. Instead I wrote a rake task saved as: lib/tasks/faker.rake.

Here is my code

  desc "Insert 100 projects using the faker gem"
  task :insert_projects => :environment do
    require 'faker'
    1..100.times do |i|
      b = Project.create( :name => Faker::Company.name,
                            :slogan => Faker::Company.bs)
    end
    puts "Faked project records"
  end

Originally I used .create! but I found occasionally there were conflicting records so a .save may pass false, now it won’t fail if it passes false and will carry on with the rest.