Nix
Nix

Reputation: 68

Rails Faker - How to generate a custom domain email?

Ideally I want to create a fake email based on the Faker generated email, but I want to achieve something like: [email protected]. The documentation shows you can do it for the first part but not the actual domain. Is there a way to achieve this?

20.times do
  u = User.new(first_name: Faker::Name.first_name,               
               last_name:  Faker::Name.last_name,
               email: Faker::Name.first_name"@THISPART.com",
               )
  u.save
end

Upvotes: 1

Views: 7693

Answers (3)

Deepak Mahakale
Deepak Mahakale

Reputation: 23671

Update Dec 2019:

Faker version v2.8.0 introduced the domain support - Release v2.8.0

Now, It is possible to pass the domain while creating the email address.

Following are the possible options:

Faker::Internet.email #=> "[email protected]"
Faker::Internet.email(name: 'Nancy') #=> "[email protected]"
Faker::Internet.email(name: 'Janelle Santiago', separators: '+') #=> [email protected]"
Faker::Internet.email(domain: 'example.com') #=> [email protected]"

Note: Above code sample is from the faker documentation

Old Answer:

Well there is no such provision to pass domain name to the method

But, you can make use of Faker::Internet.user_name

User.new(
  first_name: Faker::Name.first_name,               
  last_name:  Faker::Name.last_name,
  email:      "#{Faker::Internet.user_name}@customdomain.com"
)

Upvotes: 11

Haseeb A
Haseeb A

Reputation: 6122

Recent versions of Faker has a built in support for custom email subdomains.

Faker::Internet.email(domain: 'customdomain.com')

Upvotes: 0

everyman
everyman

Reputation: 3407

I think you just missed the string concat: +

 :006 > Faker::Name.first_name+"@THISPART.com"
 => "[email protected]" 

And if you meant keeping the same name, save it before:

fn = Faker::Name.first_name
sn = Faker::Name.last_name

u = User.create(
          :forename => fn,
          :surname => sn,
          :email => "#{fn}.#{sn}@yourdomain.net",

Faker::Name.first_name will always generate a new random value.

Upvotes: 3

Related Questions