Code Monkey home page Code Monkey logo

faker's Introduction

logotype a happy-07

Faker

Tests Gem Version Inline docs Test Coverage Maintainability

Faker is a port of Perl's Data::Faker library. It's a library for generating fake data such as names, addresses, and phone numbers.

Faker helps you generate realistic test data, and populate your database with more than a couple of records while you're doing development.

It comes in very handy for taking screenshots (taking screenshots for a personal project) and it was the original impetus for the creation of this gem).

Quick links

Table of Contents

Notes

  • While Faker generates data at random, returned values are not guaranteed to be unique by default. To explicitly specify when you require unique values, see Ensuring Unique Values. Values also can be deterministic if you use the deterministic feature, see Deterministic Random
  • This is the main branch of Faker and may contain changes that are not yet released. Please refer to the README of your version for the available methods. The list of all versions is available here.

Getting Started

Start by including faker in your Gemfile:

gem 'faker'

Then run bundle install.

Usage

Here are some examples of how to use Faker:

require 'faker'

Faker::Name.name      #=> "Christophe Bartell"

Faker::Address.full_address #=> "5479 William Way, East Sonnyhaven, LA 63637"

Faker::Markdown.emphasis #=> "Quo qui aperiam. Amet corrupti distinctio. Sit quia *dolor.*"

Faker::TvShows::RuPaul.queen #=> "Violet Chachki"

Faker::Alphanumeric.alpha(number: 10) #=> "zlvubkrwga"

Faker::ProgrammingLanguage.name #=> "Ruby"

For a complete list of the generators, see Generators.

A note about the Generators versions

If you get a uninitialized constant Faker::[some_class] error, your version of the gem is behind main.

To make sure that your gem is the one documented here, change the line in your Gemfile to:

gem 'faker', :git => 'https://github.com/faker-ruby/faker.git', :branch => 'main'

The generators have the @faker.version tag on top of their implementation. From the tags, you can identify the version the generator was added:

# Faker::TvShows::ParksAndRec.character

# @faker.version 1.9.0
def character
  fetch('parks_and_rec.characters')
end

Ensuring unique values

To ensure Faker generates unique values, prefix your method call with unique:

Faker::Name.unique.name # This will return a unique name every time it is called

If too many unique values are requested from a generator that has a limited number of potential values, a Faker::UniqueGenerator::RetryLimitExceeded exception may be raised. It is possible to clear the record of unique values that have been returned, for example between tests.

Faker::Name.unique.clear # Clears used values for Faker::Name
Faker::UniqueGenerator.clear # Clears used values for all generators

You also can give some already used values to the unique generator if you have collisions with the generated data (i.e: using FactoryBot with random and manually set values).

# Usage:
# Faker::<generator>.unique.exclude(method, arguments, list)

# Add 'azerty' and 'wxcvbn' to the string generator with 6 char length
Faker::Lorem.unique.exclude :string, [number: 6], %w[azerty wxcvbn]

Deterministic Random

Faker supports seeding of its pseudo-random number generator (PRNG) to provide deterministic output of repeated method calls.

Faker::Config.random = Random.new(42)
Faker::Company.bs #=> "seize collaborative mindshare"
Faker::Company.bs #=> "engage strategic platforms"
Faker::Config.random = Random.new(42)
Faker::Company.bs #=> "seize collaborative mindshare"
Faker::Company.bs #=> "engage strategic platforms"

Faker::Config.random = nil # seeds the PRNG using default entropy sources
Faker::Config.random.seed #=> 185180369676275068918401850258677722187
Faker::Company.bs #=> "cultivate viral synergies"

Customization

You may want Faker to print information depending on your location in the world. To assist you in this, Faker uses the I18n gem to store strings and formats to represent the names and postal codes of the area of your choosing.

Just set the locale you want as shown below, and Faker will take care of the rest.

Faker::Config.locale = 'es'
# or
Faker::Config.locale = :es

To override Faker's locales, and set it on threaded server environments check out the locales README.

Minitest and Faker >= 2.22

To prevent Faker (version >= 2.22) from generating duplicate values when using Minitest, you might need to add the following to the test_helper.rb or rails_helper.rb file:

  Faker::Config.random = Random.new

See Issue #2534 for more details.

Generators

This is the full list of generators available with this gem. If you need details about any of them, make sure to consult the documentation.

NOTE: Some of the generators below aren't released yet. If you want to use them, change the line in your gemfile to:

gem 'faker', :git => 'https://github.com/faker-ruby/faker.git', :branch => 'main'
Default
Blockchain
Books
Fantasy
Travel
Creature
Games
Japanese Media
Movies
Music
Quotes
Sports
Tv Shows
Locations

Contributing

Note: We are not accepting proposals for new generators and locales. The Contributing guide has a few notes about this decision.

Take a look at the Contributing document for instructions on setting up the repo on your machine, opening bug reports, understanding the codebase, and creating a good pull request.

There is a Discord channel to discuss anything regarding improvements or feature requests.

Thank you, contributors!

Versioning

Faker follows Semantic Versioning 2.0 as defined at https://semver.org.

License

This code is free to use under the terms of the MIT license.

faker's People

Contributors

amatsuda avatar boardfish avatar bryanmytko avatar connorshea avatar danieltiringer avatar dependabot-preview[bot] avatar dependabot[bot] avatar gkunwar avatar jdufresne avatar jremes-foss avatar koic avatar kytrinyx avatar matt17r avatar mattman avatar maxmiliano avatar mrstebo avatar npauzenga avatar pascalschumacher avatar psibi avatar rubyhuntsman avatar stefannibrasil avatar stympy avatar sudeeptarlekar avatar tagliala avatar thdaraujo avatar tiagofsilva avatar vbrazo avatar yizknn avatar yujideveloper avatar zeragamba avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

faker's Issues

Japanese locale syntax error using Syck parser

Loading ja.yml with Syck parser fails:

ArgumentError: syntax error on line 4, col 586: `      state: ["北海道","青森県","岩手県","宮城県","秋田県","山形県","福島県","茨城県","栃木県","群馬県","埼玉県","千葉県","東京都","神奈川県","新潟県","富山県","石川県","福井県","山梨県","長野県","岐阜県","静岡県","愛知県","三重県","滋賀県","京都府","大阪府","兵庫県","奈良県","和歌山県","鳥取県","島根県","岡山県","広島県","山口県","徳島県","香川県","愛媛県","高知県","福岡県","佐賀県","長崎県","熊本県","大分県","宮崎県","鹿児島県","沖縄県"]'

Syck is default parser in ruby 1.8.7 and switched on in 1.9.3 by some gems. Even worse, for some unknown reason ja.yml is parsed even if Rails project does not use Japanese locale.

Problem is reproducible without any gems installed. Tested under OSX and Linux.
Assuming ja.yml is in current directory and ruby version is 1.9.3, run in irb:

require 'rubygems'
require 'yaml'
YAML.load_file('ja.yml') # loaded without error
YAML::ENGINE.yamler = 'syck'
YAML.load_file('ja.yml') # throws ArgumentError

Dates and number generator

Has this been implemented in the current faker released or master branch? I really like these methods and makes it so much easier to use. I can't find these methods any where in the source code.

#73

The array extension method :sample throw an argument error when the array is empty

Hi, stympy

I am using the newest version of faker, seems the extension of array method :sample breaks the default ruby :sample when the array is empty and there gives an argument.

  • ruby default :sample
    [].sample(3) => []
  • faker extension :sample
    [].sample(3) => wrong number of arguments (1 for 0)

Though this example seems a little wired, I really meet this error in my project. Please fix it.

Whitespace not normalized for UK postcodes

2.0.0-p247 > Faker::Address.postcode
=> "R3V  9JY"

There are two space characters, when there should only be one. So far I've only encountered this for postcodes in the UK.

Switch to 18n is not playing nice with rails

Faker should not change I18n locale (however this can be easly fixed by setting Faker::Config.locale).

Other problem after updating faker gem, when running specs in rails application is lots of failing tests:

Expected errors to include "translation missing: en.errors.messages.blank" when user_id is set to nil, got errors: user_id translation missing: en.activerecord.errors.models.billing.attributes.user_id.blank (nil)app_id translation missing: en.activerecord.errors.models.billing.attributes.app_id.blank (nil)

Rails 2.3.10, Ruby ree-1.8.7-2010.02

Do not downcase default locale

In Faker::Config.locale the value from I18n.locale is downcased. This is the source for failures if regional extensions are used, which are usually uppercase (e.g. de-CH). So the correct implementation should be:

@Locale || I18n.locale

Faker::Internet::fix_umlauts(String) does not clear all special characters

Hello,

fix_umlauts is currently implemented this way:

  def fix_umlauts(string)
    string.gsub(/[äöüß]/i) do |match|
        case match.downcase
            when "ä" 'ae'
            when "ö" 'oe'
            when "ü" 'ue'
            when "ß" 'ss'
        end
    end
  end

This should be extended so that characters like é, â, ç etc. are also replaced with their respective non-accented variants. E.g.

  def fix_umlauts(string)
    string.gsub(/[äöüß]/i) do |match|
        case match.downcase
            when "ä" 'ae'
            when "ö" 'oe'
            when "ü" 'ue'
            when "ß" 'ss'
        end
    end
    string.parameterize     # requires Rails ActiveSupport, however
  end

phone_number can generate invalid US numbers

I'm using the phone library to parse phone numbers, and it does not allow invalidly-formatted phone numbers. An example is that US area codes are not allowed to start with 1 (and 0, I believe), but Faker will generate numbers with these invalid area codes. Would it be possible to restrict the range of numbers used in generating area codes for Faker phone numbers?

Breaks existing app

The latest version upgrade broke my specs with this error:
uninitialized constant I18n::Backend::Fallbacks (NameError)

Faker::Address administrative levels as ISO 3166-1

As explained here: http://en.wikipedia.org/wiki/Table_of_administrative_country_subdivisions_by_country, each country has its own administrative subdivision. These subdivision can be grouped in 3 levels (the fourth usually matches with the city name).
When making a data structure to contain international addresses, is usefull to follow these subdivisions.
It should be easy to add administrative_level1, administrative_leve2 and administrative_leve3 generators to Faker::Address.
The current generators applies well only for US.
What do you think about?

setting a different locale (FR) generates wrong zip codes

I tried to set a different locale as follows;

def make_clients
Faker::Config.locale = :fr
99.times do |n|
firstname = Faker::Name.first_name
lastname = Faker::Name.last_name
street = Faker::Address.street_name
house = Faker::Address.building_number
city = Faker::Address.city
zipcode = Faker::Address.zip_code
puts "zipcode: #{zipcode}"
country = Faker::Address.country
password = "password"
Client.create!(firstname: firstname,
lastname: lastname,
street: street,
house: house, zipcode: zipcode,
city: city, country: country)
end

end

The zip code generated was:
zipcode: 79623-1275
rake aborted!
Validation failed: Zipcode is too long (maximum is 5 characters). In France zipcodes are of 5 digits only. How to fix that ?
Thank you.

Poor result from Faker::Internet.user_name in ja locale

Faker::Internet.user_name uses localized Faker::Name.first_name / last_name and eliminates accented alphabets by gsub(/\W/, ''), but as Japanese is non-alphabet script, it removes almost all characters from generated names.

Result: Faker::Internet.user_name returns only ".", "_" and "".

Not a valid character (0x80) - problem with locales

Hi,

I had some strange ActionView template rendering exceptions, in a fat Rails application, that were caused by some problems with the en-au.yml locale. I verified in all known to me ways that my app is configured to use utf8 encoding, but the problem persisted. Then I took a radical action and removed directly all sections in the yml file that looked strange to me. After a couple of iterations with this ugly cutting, going through Brazilian Portuguese and French, issue was gone.

I am not sure whether this is an issue with the faker gem or not, but just wanted to let you know. I executed Linux's file info commands and they displayed 'character encoding:unknown' when run against some of the locales. Are all locales files utf8 compliant ?

The exact error message is:

ActionView::Template::Error ((.../WEB-INF/gems/gems/faker-1.0.1/lib/locales/pt-br.yml): 'reader' unacceptable character '�' (0x81) special characters are not allowed|

Kindest Regards,
Krum.

Faker::Address.uk_postcode can generate invalid postcodes.

This is the regex I've been using to validate them:

/^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$/

Which seems to be the correct one, as taken from StackOverflow

Faker generated BI56 3QX for me, which when you search in Google Maps is not recognised.

Generating phone numbers with specific format

I created a en-us.yml file with this content

en-us:
  faker:
    phone_number:
      formats:
        - "(#{PhoneNumber.area_code}) #{PhoneNumber.exchange_code}-#{PhoneNumber.subscriber_number}"

Then this is what I get:

[1] pry(main)> Faker::Config.locale = 'en-us'
=> "en-us"
[2] pry(main)> Faker::PhoneNumber.cell_phone
=> "(9{PhoneNumber.area_code}) 8{PhoneNumber.exchange_code}-9{PhoneNumber.subscriber_number}"

Any idea why?

Thanks,
SB

Overly long names

Hi all,

thank you for Faker.

I'm using faker 1.1.2 in Rails 4 and it seems I get really long names:

irb(main):013:0> Faker::Name.name
=> "Enzo Lucas Mathis Nathan Thomas Hugo Théo Tom  Louis  Raphaël  Clément  Léo  Mathéo Maxime Alexandre  Antoine  Yanis  Paul Baptiste Alexis Gabriel  Arthur Jules  Ethan  Noah Quentin  Axel Evan Mattéo Romain Valentin Maxence  Noa  Adam Nicolas  Julien Mael Pierre Rayan  Victor Mohamed  Adrien Kylian Sacha  Benjamin Léa Clara Manon Chloé Camille Ines  Sarah Jade  Lola  Anaïs Lucie Océane  Lilou Marie Eva Romane  Lisa  Zoe Julie Mathilde  Louise  Juliette  Clémence  Célia Laura Lena  Maëlys  Charlotte Ambre Maeva Pauline Lina  Jeanne  Lou Noémie  Justine Louna Elisa Alice Emilie  Carla Maëlle  Alicia  Mélissa Martin Bernard Dubois Thomas Robert Richard Petit Durand Leroy Moreau Simon Laurent Lefebvre Michel Garcia David Bertrand Roux Vincent Fournier Morel Girard Andre Lefevre Mercier Dupont Lambert Bonnet Francois Martinez Legrand Garnier Faure Rousseau Blanc Guerin Muller Henry Roussel Nicolas Perrin Morin Mathieu Clement Gauthier Dumont Lopez Fontaine Chevalier Robin Masson Sanchez Gerard Nguyen Boyer Denis Lemaire Duval Joly Gautier Roger Roche Roy Noel Meyer Lucas Meunier Jean Perez Marchand Dufour Blanchard Marie Barbier Brun Dumas Brunet Schmitt Leroux Colin Fernandez Pierre Renard Arnaud Rolland Caron Aubert Giraud Leclerc Vidal Bourgeois Renaud Lemoine Picard Gaillard Philippe Leclercq Lacroix Fabre Dupuis Olivier Rodriguez Da silva Hubert Louis Charles Guillot Riviere Le gall Guillaume Adam Rey Moulin Gonzalez Berger Lecomte Menard Fleury Deschamps Carpentier Julien Benoit Paris Maillard Marchal Aubry Vasseur Le roux Renault Jacquet Collet Prevost Poirier Charpentier Royer Huet Baron Dupuy Pons Paul Laine Carre Breton Remy Schneider Perrot Guyot Barre Marty Cousin"

Cell Phone Numbers Have Extensions

As far as I know this is not valid:

rails [3.2.16]$ Faker::VERSION
=> "1.2.0"
rails [3.2.16]$ Faker::PhoneNumber.cell_phone
=> "903.706.7054 x438"

(misunderstanding) ru locale does not output russian ru.yml entries

UPDATE:
Duh! I am stupid. :ru is not part of 1.2.0 release. misunderstanding

Issue:
env
ruby 2.0
faker 1.2.0
I18n 0.6.9)

test in irb:
require 'faker'
Faker::Config.locale = :ru
Faker::Name.name

=> outputs english names instead of expected russian

I would appreciate if somebody can tell me if they see the same issue in irb. I may be going mad because the spec tests pass but in regular usage I don't get the russian strings.

undefined method `Number' for Faker:Module

Using faker (1.2.0) on Rails 4.0.0 I get:
undefined method `Number' for Faker:Module

I am using it to populate my model attribute as such:

:year => Faker::Number.number(4)

Anyone encountered this problem?

Faker and Zeus don't work together

Hi @stympy,

I've ran into some problems with Faker and Zeus #412 and I was hoping you had some ideas about this. Seems Faker causes some problems with the Psych gem or with Zeus, but I can't figure it out.

Any ideas on this?

Cheers.

Crashes with Rails 2.3.10

Was using Faker with Rails 2.3.5 and everything was OK. After updating to 2.3.10 I get this error:

ree-1.8.7-2010.02 :002 > Faker::Lorem.words
NoMethodError: undefined method `shuffle' for "translation missing: pt.faker.lorem.words":String
    from /Users/lucashungaro/.rvm/gems/ree-1.8.7-2010.02@viaranking/gems/faker-0.9.5/lib/faker/lorem.rb:5:in `words'
    from (irb):2

i18n breaks 1.8.7 and ree

Using faker in a gem that I test/use on 1.8.7 and REE, I got a weird stack trace parsing the Japanese YAML file. Don't have 1.8.7 locally ATM, so forked the repo and set it up on Travis:

http://travis-ci.org/#!/davetron5000/faker/jobs/2473018

Basically, calls to translate load all(?) the YAML files, and they are in a format incompatible with 1.8.7/REE. I will try to look into it when I'm not in the air and can install 1.8.7, but am logging this anyway, in case someone else sees an obvious solution.

Translation missing: `en.faker.name.name_name` when using `:fr` locale

Hi,

I've this error when calling Faker::Name.name in a rspec :

I18n::MissingTranslationData:
  translation missing: en.faker.name.name_name

There is no error when calling this method from rails console.

I'm using fr locale via

Faker::Config.locale = 'fr'

It seems all is fine if I switch to en or it for example.

Add consistency to Faker

Hi,

I think Faker should implement something like a Provider to provides coherent objects.

#Easy example
user = Faker::User
user.firstname #Gina
user.gender #female

The firstname and the gender are coherent.

#Really complex example
addr = Faker::Address 
addr.lattitude=48.858545
addr.longitude=2.294470
addr.fullAdress=Champ de Mars 5 Avenue Anatole France 75007 Paris

The GPS and the adress are coherent.

Suggestions for other types of data

I'm interested in using faker to fake other data. Specifically, I would like to use it in a situation more like a MadLib, but not for those purposes specifically.

I'd like a way to be able to create adjectives, nouns, verbs etc, and this seems like a reasonable library for including something like this. I made some changes to a copy of faker locally for my purposes, and didn't know if it would be worth pulling back into the project.

Let me know.

NoMethodError: undefined method `[]' for nil:NilClass

[master] ~/dev/my_proj → irb
ruby-1.9.2-p290 :001 > require 'faker'
=> true
ruby-1.9.2-p290 :002 > Faker::Lorem.url
NoMethodError: undefined method []' for nil:NilClass from /Volumes/HDDisk/Users/jetienne/.rvm/gems/ruby-1.9.2-p290/gems/faker-1.0.1/lib/faker.rb:89:inmethod_missing'
from (irb):2
from /Volumes/HDDisk/Users/jetienne/.rvm/rubies/ruby-1.9.2-p290/bin/irb:16:in `

'

Faker::Lorem.words(500) produces only 249 words without warning or error!

 irb(main):002:0> Faker::Lorem.words(500).size
 => 249

I had to spend couple of hours before I could figured why my test were failing.
Ideally I would expect lib to throw an error or auto include supplement words if the size of standard words is smaller than requested number of words.

What would be the right way? throw an error or auto include additional words?

French is heavily broken

Tests done with Faker 1.1.2 :

Faker::Address.street_name
=> "Place Faker::Address"

Faker::Address.city
=> ""

Faker::Name.first_name
=> "Enzo Lucas Mathis Nathan Thomas Hugo Théo Tom Louis Raphaël Clément Léo Mathéo Maxime Alexandre Antoine Yanis Paul Baptiste Alexis Gabriel Arthur Jules Ethan Noah Quentin Axel Evan Mattéo Romain Valentin Maxence Noa Adam Nicolas Julien Mael Pierre Rayan Victor Mohamed Adrien Kylian Sacha Benjamin Léa Clara Manon Chloé Camille Ines Sarah Jade Lola Anaïs Lucie Océane Lilou Marie Eva Romane Lisa Zoe Julie Mathilde Louise Juliette Clémence Célia Laura Lena Maëlys Charlotte Ambre Maeva Pauline Lina Jeanne Lou Noémie Justine Louna Elisa Alice Emilie Carla Maëlle Alicia Mélissa"

Faker::Company.buzzwords
=> ["Adaptive", "Advanced", "Ameliorated", "Assimilated", "Automated", "Balanced", "Business-focused", "Centralized", "Cloned", "Compatible", "Configurable", "Cross-group", "Cross-platform", "Customer-focused", "Customizable", "Decentralized", "De-engineered", "Devolved", "Digitized", "Distributed", "Diverse", "Down-sized", "Enhanced", "Enterprise-wide", "Ergonomic", "Exclusive", "Expanded", "Extended", "Face to face", "Focused", "Front-line", "Fully-configurable", "Function-based", "Fundamental", "Future-proofed", "Grass-roots", "Horizontal", "Implemented", "Innovative", "Integrated", "Intuitive", "Inverse", "Managed", "Mandatory", "Monitored", "Multi-channelled", "Multi-lateral", "Multi-layered", "Multi-tiered", "Networked", "Object-based", "Open-architected", "Open-source", "Operative", "Optimized", "Optional", "Organic", "Organized", "Persevering", "Persistent", "Phased", "Polarised", "Pre-emptive", "Proactive", "Profit-focused", "Profound", "Programmable", "Progressive", "Public-key", "Quality-focused", "Reactive", "Realigned", "Re-contextualized", "Re-engineered", "Reduced", "Reverse-engineered", "Right-sized", "Robust", "Seamless", "Secured", "Self-enabling", "Sharable", "Stand-alone", "Streamlined", "Switchable", "Synchronised", "Synergistic", "Synergized", "Team-oriented", "Total", "Triple-buffered", "Universal", "Up-sized", "Upgradable", "User-centric", "User-friendly", "Versatile", "Virtual", "Visionary", "Vision-oriented"]

UK Postcode still generating 2 spaces between elements

Hi, this is my first GITHUB post and I am new to ruby so please bear with me. I have looked through the issues logged about faker and have spotted this issue reported previously and fixed. However, having checked I am on the latest version of faker (1.2.0) I am still getting these problems.

My development environment is as follows:

  • ruby 1.9.3p448 (2013-06-27 revision 41675) [i686-linux]
  • Rails 4.0.2
  • faker (1.2.0)
  • i18n (~> 0.5)

If I run IRB and setup the local for UK then generate a postcode you can see below that it has produced a postcode with two spaces:

rails console
Loading development environment (Rails 4.0.2)
1.9.3p448 :001 > Faker::Config.locale = 'en-gb'
=> "en-gb"
1.9.3p448 :002 > Faker::Address.postcode
=> "WM5 6JY"

Having run this several more times I get the following results:

=> "YS3 8BA" [ Invalid ]
=> "I78 6DJ" [ Invalid ]
=> "YH7 4FN" [ Valid ]
=> "S6H 9PU" [ Valid ]
=> "Y4V 9YP" [ Valid ]
=> "ZE1 1LN" [ Valid ]
=> "W1 2QB" [ Invalid ]
=> "GD7X 7GA" [ Invalid ]
=> "S35 7AL" [ Invalid ]
=> "W9N 0JR" [ Valid ]
=> "G0 5BJ" [ Valid ]
=> "TL8 5BL" [ Invalid ]
=> "YF9P 3DJ" [ Invalid ]
=> "YG9W 9LL" [ Valid ]

The results are bizarre because it does produce both valid and invalid formats that follow the same postcode standards.

For example,
"YS3 8BA" and "YH7 4FN" are both in the format AAN NAA, yet one has a single space and the other has 2 spaces.

"GD7X 7GA" and "YG9W 9LL" are both in the format AANA NAA and again one has a single space and the other has 2 spaces.

I can get around this using the squeeze method as suggested by one of the other posters but thought I should report the bug because the fix doesn't seem to have worked.

Faker::Address.postcode.squeeze(" ")

I checked that the regular expression you are using in Faker to see if it would return invalid for postcodes with 2 spaces (in the correct format). The regex you are using is as follows:

[A-PR-UWYZ][A-HK-Y]?[0-9][ABEHMNPRVWXY0-9]? [0-9][ABD-HJLN-UW-Z]{2}

I checked this using Rubular and Expresso tools using the postcode "US6P 7AD" and both indicated this does not match the regex. Removing the space does produce a valid match.

Faker breaks string interpolation on rails 2.3.x with 1.8.7-p352

Will try and push a demo app with test tomorrow if I get time. However, (quick and dirty) steps to reproduce are:

  • setup a new 2.3.x (I'm using 14) bare app with a Gemfile that has only installs gem 'rails' and gem 'faker';
  • bundle install;
  • script/console;
  • at the prompt, type "%{a}" % {:a => 1}

The result will be:

ArgumentError: malformed format string - %{
        from (irb):1:in `%'
        from (irb):1

The various :require => nil and I18n.reload! workarounds suggested in issue 5 do not seem to sort the problem.

Faker::Base.regexify(re) doesn't work with comments in method code

using Rails 3.2.3 / Ruby 1.9.3

tested in console :
re = /^[A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}$/
re.class
=> Regexp
Faker::Base.regexify(re)
NoMethodError: undefined method []' for nil:NilClass from /Users/yves/.rvm/gems/ruby-1.9.3-p125@rails32/gems/faker-1.0.1/lib/faker.rb:89:inmethod_missing'

I forked Faker and removed the comments in the regexify(re) method .., then tested again :
re = /^[A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}$/
re.class
=> Regexp
Faker::Base.regexify(re)
=> "ZOM 6BB"

Release FR locale first/last name correction to Rubygems

First names and last names for FR locale are not working correctly on the Rubygems version since it's the 1.1.2 and it does not include commit 5fbaedc.

Would be great not to run into this not-so-evident-issue when using the Rubygems version.

Thanks in advance!

Setting locale (FR) does not change country

I tried to set up a locale as suggested:

Faker::Config.locale = :fr

I tried to do that in 2 different ways:

  • by putting it in spec_helper config block:
require 'faker'
...

RSpec.configure do |config|
...
Faker::Config.locale = :fr
...
end
  • by putting it directly in a spec example file (clients_controller_spec.rb):
require 'spec_helper'
require 'faker'

describe ClientsController do
  before { Faker::Config.locale = :fr }
...
end

In both cases the country value was NOT correct:

  • CONGO
  • SENEGAL
  • BARBADOS
  • EQUATORIAL GUINEA

etc.

The only solution I found was to set a country as follows in my Factory file:

factory :client do
...
  country    { Faker::Address.default_country }
....
end

Is it a right way ?
Any idea ?

Thank you.

Produced with faker version 1.3.0, Ruby 2.0.0, Windows XP box.

en-gb street_address

When setting the local to the UK

Faker::Config.locale = "en-gb"

Using

Faker::Address.street_address

causes the following error NoMethodError: undefined method 'building_number' for Faker::Address:Class

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.