EzDevInfo.com

faker.js

generate massive amounts of fake data in Node.js and the browser

Why does output of faker::lorem produce dashes at the beginning of the string?

Using faker gem with rails to generate some fake data. When I use faker::lorem the output includes dashes in front of the string.

namespace :db do
  desc "Fill database with sample data"
  task populate: :environment do
    7.times do |l|
      line = Line.create!(sentence: Faker::Lorem.sentences(2))
    end
  end
end

Like:

---
- Odit consectetur perspiciatis delectus sunt quo est.
- Tempore excepturi soluta aliquam perferendis.

Any idea why this function returns the Lorem with dashes? Easiest way to strip them out?


Source: (StackOverflow)

How to get future date in Faker

How do I get future dates with:

https://github.com/fzaninotto/Faker#fakerproviderdatetime

dateTime($max = 'now')  

i.e. what should the $max value be for datetime in the future


Source: (StackOverflow)

Advertisements

Change faker gem phone number format

Is there a way to control the format of the Phone number generated by faker?

When I call:

Faker::PhoneNumber.cell_phone.to_i

I end up getting the wrong value.

I also would like to not have extensions.


Source: (StackOverflow)

FactoryGirl + Faker - same data being generated for every object in db seed data

I am using FactoryGirl and Faker to generate user objects in my seeds.rb file but for some reason the exact same user is being created and rake db:seed is failing because of an email uniqueness validation.

Factory for users:

#users.rb
require 'faker'

FactoryGirl.define do
  factory :user do
    first_name            Faker::Name.first_name
    last_name             Faker::Name.last_name
    phone                 Faker::PhoneNumber.cell_phone
    email                 Faker::Internet.email
    password              "password"
    password_confirmation "password"
  end
end

And the code in seeds.rb file:

#seeds.rb
rand(5..11).times { FactoryGirl.create(:user) }

Error:

ActiveRecord::RecordInvalid: Validation failed: Email has already been taken

If I open the console and use FactoryGirl.create(:user) I get the same results...same object is being created over and over even though if I run just Faker::Internet.email several times I'll get several e-mails.

FactoryGirl:

[1] pry(main)> FactoryGirl.create(:user)
...
=> #<User id: 3, first_name: "Osvaldo", last_name: "Wunsch", email: "willy@damore.net", phone: "(912)530-4949 x64848", created_at: "2014-07-31 20:57:27", updated_at: "2014-07-31 20:57:27", encrypted_password: "$2a$10$mxWC7yLYR0m/Sw8MO6Lyru.xuTHCdCEuM9Orx3LXGApF...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil>
[2] pry(main)> FactoryGirl.create(:user)
...
ActiveRecord::RecordInvalid: Validation failed: Email has already been taken

Faker by itself:

[3] pry(main)> Faker::Internet.email
=> "hobart_purdy@goodwinmills.org"
[4] pry(main)> Faker::Internet.email
=> "pierce_brekke@gislasonrolfson.net"

What am I missing here? Why is Faker producing the same data every time when used through FactoryGirl?


Source: (StackOverflow)

Use Faker gem to generate correlated city, postal code, country code values

Is there a way to get the Faker gem to generate 'correlated' city and country code values?

For example,

  • Vancouver, CA
  • Minneapolis, MN

I'm doing this:

FactoryGirl.define do
  factory :location do
    ...
    city {Faker::Address.city}
    country_code {['US', 'CA'].sample}
    ...
  end
end

But there is no guarantee that the city will actual reside in country_code.

I'd settle for something like:

postal_code {Faker::Address.postcode(['US', 'CA'].sample) }

Which I could then geocode to get the other values.


Source: (StackOverflow)

Issue with Faker gem

I installed Fabrication and Faker in my Rails 4 project

I created a fabrarication object:

Fabricator(:course) do
  title { Faker::Lorem.words(5) }
  description { Faker::Lorem.paragraph(2) } 
end

And I'm calling the Faker object within my courses_controller_spec.rb test:

require 'spec_helper'

describe CoursesController do
  describe "GET #show" do
    it "set @course" do
      course = Fabricate(:course)
      get :show, id: course.id
      expect(assigns(:course)).to eq(course)
    end
    it "renders the show template"
  end
end

But for some reason, the test failes at line 6:

course = Fabricate(:course)

the error message is:

Failure/Error: course = Fabricate(:course)
 TypeError:
   can't cast Array to string

Don't know exactly why this is failing. Has anyone experienced the same error message with Faker?


Source: (StackOverflow)

How to handle foreign key in FactoryGirl

I have a user model and a follower model, such that a user can have many followers. So in schema of follower model I have user_id column and a follower_by_user_id column. So in follower model a user can be followed by many followers. User id's are stored in user_id column and followers id's are whose id's are stored in as followed_by_user_id.

class User < ActiveRecord::Base
 has_many :followed_users, :class_name => 'Follower', :foreign_key => 'user_id'
 has_many :followers, :class_name => 'Follower', :foreign_key => 'followed_by_user_id'

 validates :email, presence: true, format:{ with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i}

 validates :name,presence:true
end

Above is user model

class Follower < ActiveRecord::Base
 belongs_to :user
 belongs_to :followed_by_user, :class_name => 'User', :foreign_key => 'followed_by_user_id'

 validates :user, :followed_by_user, presence:true
 validates_associated :user, :followed_by_user
end

above is follower model

FactoryGirl.define do 
factory :user do
  name {Faker::Name.name}
  email {Faker::Internet.email}
end 

factory :follower do
  user
  followed_by_user_id
end

followed_by_user_id is basically a user id only, or we can say user_id is foreign key for followed_by_user_id column. Im plain English followed_by_user_id is an id of an user who is following to some other user. So If any body can help how to include this foreign key relationship in follower factory for follower_by_user_id column?

Thanks in advance.


Source: (StackOverflow)

Use faker.js to generate the form for casperjs

Casperjs can filling & submitting forms, but you need put it by your self and change it every time. Faker.js can generate the faker date which the form need. So, I just think how to combine it together? For example like this code::

var casper = require('casper');

var Faker = require('./Faker');

casper.start('http://contact.form', function() {

    this.fill('form#contact-form', {

     'name':   'Chuck Norris',

     'email':  'chuck@norris.com',

    }, true);

});

casper.start('http://contact.form', function() {

    this.fill('form#contact-form', {

     'name':   Faker.Name.findName(),

     'email':  Faker.Internet.email(),

    }, true);

});

Do you think is this correct or not?


Source: (StackOverflow)

Faker Package, Database Seeder Issues

I'm pretty deep down the rabbit hole on this one. This question is actually part of a bigger question related to getting my Laravel app to function correctly. Here's the link to the other question if you'd like to see more about my troubles: Wrongful ModelNotFoundException in Laravel.

So, now I'm trying to use the database seeder package, Faker, to populate my database. I've installed it correctly, but I'm having trouble making it work for me beyond the User table. Here's what I've got for my UserTableSeeder:

class UserTableSeeder extends Seeder {

  public function run()
  {
    $faker = Faker\Factory::create();

    for ($i = 0; $i < 100; $i++)
    {
        User::create(
            [
                'id' => $faker->randomDigit,
                'first_name' => $faker->firstName,
                'last_name' => $faker->lastName,
                'email' => $faker->freeEmail,
                'notify' => $faker->randomElement($array = ['y', 'n']),
                'created_at' => $faker->dateTime($max = 'now'),
                'updated_at' => $faker->dateTime($max = 'now')
            ]
        );
    }
  }
}

This is half-working when I run php artisan db:seed; it creates only a dozen rows or so. My users table has seven columns:

id (its type is integer),
first_name(varchar),
last_name(varchar),
email(varchar),
notify(enum),
created_at(timestamp),
and updated_at(timestamp)

Any code that would handle this correctly or serve as a template for a similar table would be greatly appreciated. Thanks folks.


Source: (StackOverflow)

Rails Faker how to create custom method

I'm using rspec and faker for testing and I want to add a cuestom field on faker, I had followed this instructions:

https://github.com/stympy/faker#customization

So in my rails_helper.rb I have this line:

Faker::Config.locale = :ca

And in my ca.yml under config/locales folder I have:

faker:
    internet:
      usefuldata: [AAAAA,BBBBB]

And when I made Faker::Internet.usefuldata it returns undefined method 'usefuldata' for Faker::Internet:Class. And I want that Faker::Internet.usefuldata return AAAAA or BBBBB.

Thanks in advance.


Source: (StackOverflow)

My Ideas factory is broken (unique title validation)

Here's a FactoryGirl factory:

FactoryGirl.define do
  factory :idea do
    title Faker::Lorem.sentence
    note Faker::Lorem.sentences(2)
    status "available"
  end
end

And here's idea model:

class Idea < ActiveRecord::Base
  attr_accessible :note, :status, :title
  validates :title,  presence: true, uniqueness: true, length: {minimum: 20}
  validates :status, presence: true, inclusion: {in: %w(pending available claimed overdue submitted aborted rejected)}
  belongs_to :user
end

Now, when I type into my Rails console t1 = FactoryGirl.create(:idea), no problem, I get an idea. But when I then type t2 = FactoryGirl.create(:idea) it crashes, saying that the validation fails: ActiveRecord::RecordInvalid: Validation failed: Title has already been taken

And indeed, I see in the SQL dump that FactoryGirl tried using the same exact string twice:

1.9.3p327 :002 > t1 = FactoryGirl.create(:idea)
   (0.0ms)  begin transaction
  Idea Exists (1.8ms)  SELECT 1 AS one FROM "ideas" WHERE "ideas"."title" = 'Eligendi sint quod quia alias sed sit vitae repellendus.' LIMIT 1
  SQL (7.4ms)  INSERT INTO "ideas" ("created_at", "note", "status", "title", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?, ?)  [["created_at", Thu, 27 Dec 2012 18:20:47 UTC +00:00], ["note", ["Aut placeat mollitia.", "Adipisci in est eos."]], ["status", "available"], ["title", "Eligendi sint quod quia alias sed sit vitae repellendus."], ["updated_at", Thu, 27 Dec 2012 18:20:47 UTC +00:00], ["user_id", nil]]
   (6.3ms)  commit transaction
 => #<Idea id: 1, title: "Eligendi sint quod quia alias sed sit vitae repelle...", note: ["Aut placeat mollitia.", "Adipisci in est eos."], status: "available", created_at: "2012-12-27 18:20:47", updated_at: "2012-12-27 18:20:47", user_id: nil> 
1.9.3p327 :003 > t2 = FactoryGirl.create(:idea)
   (0.1ms)  begin transaction
  Idea Exists (2.7ms)  SELECT 1 AS one FROM "ideas" WHERE "ideas"."title" = 'Eligendi sint quod quia alias sed sit vitae repellendus.' LIMIT 1
   (0.0ms)  rollback transaction
ActiveRecord::RecordInvalid: Validation failed: Title has already been taken

But when I repeatedly run Faker::Lorem.sentence in the console, I keep getting random, different sentences.

So, why does Faker and/or FactoryGirl decide to use the same exact string even though it's supposed to be random?


Source: (StackOverflow)

How to resolve name collision between i18n's Hash#slice and ActiveSupport's Hash#slice

I'm working on a Rails 2.3.14 project, which uses 0.6.0 of the i18n gem and 2.3.14 of the ActiveSupport gem. Both of these define a Hash#slice method (i18n's; ActiveSupport's), but they function differently: the i18n version uses Hash#fetch, and so raises an i18n/core_ext/hash.rb:4:in 'fetch': key not found (IndexError) exception if any requested key is missing, while the ActiveSupport version happily ignores missing keys, and the rest of ActiveSupport depends on that happy ignoring.

In my app, the i18n version is loading first (because, incidentally, faker is loading it as a dependency), so when ActiveSupport tries to depend on the ignore-missing-keys behavior I get the exception.

Is there a way to tell Rails to load ActiveSupport before faker and i18n?


Source: (StackOverflow)

can't populate db using rake db:populate

I am trying to populate my db using rake db:populate. I am on chapter 10.3.2 on michael hartl's book.

Even though I don't get any error messages the DB doesn't seem to be populating.

This is the sample_data.rake file I created:

  namespace :db do   desc "Fill database with sample data"   task populate: :environment do
        User.create!(:name => "Example User",
                     :email => "example@railstutorial.org",
                     :password => "foobar",
                     :password_confirmation => "foobar")
        99.times do |n|
          name  = Faker::Name.name
          email = "example-#{n+1}@railstutorial.org"
          password  = "password"
          User.create!(:name => name,
                       :email => email,
                       :password => password,
                       :password_confirmation => password)
        end   
     end 
  end

Source: (StackOverflow)

using faker gem to generate date

I'm using factory girl and faker to generate data for a rails app. The trouble is, faker's docs don't say anything about generating random dates.

Here is my existing code. As you can see, I'm unsure of how to proceed after start_date. How can I generate a date?

Thanks in advance :)

FactoryGirl.define do
  factory :registration_form do
    first_name   Faker::Name.first_name
    last_name    Faker::Name.last_name
    email        Faker::Internet.safe_email
    phone_number Faker::PhoneNumber.phone_number
    twitter      Faker::Internet.user_name
    skype        Faker::Internet.user_name
    start_date   Faker:: ???????????
  end
end

Source: (StackOverflow)

How to pass faker data result to a custom function

I'm using PhoneNumberBundle for validates phone number on my application. I'm using also NelmioAliceBundle together with AliceFixtureBundle. Having that as start point I'm writing a fixture for a entity that has a PhoneNumberBundle assert for validate the phone number. Here is a snippet of that file:

/**
 * @AssertPhoneNumber(defaultRegion="VE")
 * @ORM\Column(name="phone", type="phone_number", length=11)
 */
protected $phone;

I don't know how to use external libraries on the fixture itself so the only solution I see if to write my own faker and return the well formated number phone and pass back to the fixture. Then I did this:

TananeFakerProvider.php

class TananeFakerProvider {

    public function formatPhoneNumber($fakePhoneNumber)
    {
        return $this->container->get('libphonenumber.phone_number_util')->parse($fakePhoneNumber);
    }

}

services.yml

services:
    tanane.faker.provider:
        class: CommonBundle\Tools\TananeFakerProvider
        arguments: ["@service_container"]
        tags:
            -  { name: h4cc_alice_fixtures.provider }

And finally Orders.yml (the fixture):

FrontendBundle\Entity\Orders:
    Orders{1..50}:
        nickname: <text(15)>
        # trying to pass the fake number back to the custom faker
        phone: <formatPhoneNumber(phoneNumber())>
        email: <companyEmail()>
        fiscal_address: <address()>
        shipping_address: <address()>
        shipping_from: <randomElement(array('MRW','DOMESA', 'ZOOM'))>
        payment_type: @PaymentType*
        order_amount: <randomFloat(2)>
        bank: @Bank*
        transaction: <randomNumber()>
        comments: <sentence(15)>
        secure: <boolean(35)>
        person: <randomElement(array(@Natural*, @Legal*))> 
        status: @OrderStatus*

But I got this error:

[Symfony\Component\Debug\Exception\ContextErrorException] Notice: Use of undefined constant phoneNumber - assumed 'phoneNumber' in /var/www/html/vendor/nelmio/alice/src/Nelmio/Alice/Loader/Base.php(630) : eval()'d code line 1

So I'm passing the value in the wrong way, could any give me some help on this? Or maybe give me another idea in how to achieve this?


Source: (StackOverflow)