Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • faker gem integration in rails application

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 758
    Comment on it

    A faker gem is used to create the fake data for testing or demo purpose in rails application. It is Perl's Data::Faker library that generate different type (i.e. Address, color, code, commerce, company, date etc.) of fake data. We are generally using this gem to feed the fake records during application development. The implementation of faker gem give as below...

     

    Step1: Add faker gem into Gemfile

     

    Path: my_app/Gemfile

    1. gem install faker

     

    Step2: Run bundler

    1. bundle install

     Now, we can use the fake data in our application.

     

    Feed fake data into table: If we require some data during application development, we can feed by seed.rb file


    For example : Suppose we have a table users with columns first_name, last_name, email, address, phone and need some data during development, so we can feed data into table by below code...

     

    Add below code into seeds.rb

    Path: my_app/db/seeds.rb

    1. (0..50).each do |p|
    2. User.create(fist_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: Faker::Internet.email , address: Faker::Address.street_address , phone: Faker::Number.number(10) )
    3. # puts "Created #{p}"
    4. end

     

    Then run

    1. rake db:seed

     

    Finally our users table filled with 50 records.We can also use this gem into test case.

     

    For example: we are going to write a model unit  test-case for has_many association between country & city using faker gem data

    1. def test_country_has_many_cities_association
    2. country = create(:country, :name => Faker::Address.country, :code => Faker::Address.country_code)
    3. c1 = create(:city, country_id: country.id, :city_name => Faker::Address.city, :zip => Faker::Address.zip_code )
    4. c2 = create(:city, country_id: country.id, :city_name => Faker::Address.city, :zip => Faker::Address.zip_code)
    5.  
    6. assert_equal country.cities, [c1,c2]
    7. end

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: