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
    • 737
    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

    gem install faker

     

    Step2: Run bundler

    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

    (0..50).each do |p|
      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) )
     # puts "Created #{p}"
    end

     

    Then run

    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

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

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: