Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6567893
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T14:23:26+00:00 2026-05-25T14:23:26+00:00

Suppose I have a model user , which has a uniqueness constraint on the

  • 0

Suppose I have a model user, which has a uniqueness constraint on the email field

If I call Factory(:user) once all is well, but if I call it a second time it’ll fail with an “entry already exists” error.

I’m currently using a simple helper to search for an existing entry in the DB before creating the factory…and calling any factory I make through that helper.

It works, but it’s not entirely elegant, and considering how common I assume this problem must be, I’m guessing there’s a better solution. So, is there an inbuilt way in factory girl to return_or_create a factory, instead of just charging ahead with create()? If not, how do most folk avoid duplicate entries with their factories?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T14:23:27+00:00Added an answer on May 25, 2026 at 2:23 pm

    Simple answer: use factory.sequence

    If you have a field that needs to be unique you can add a sequence in factory_girl to ensure that it is never the same:

    Factory.define :user do |user|
      sequence(:email){|n| "user#{n}@factory.com" }
      user.password{ "secret" }
    end
    

    This will increment n each time in order to produce a unique email address such as user52@factory.com. (See https://github.com/thoughtbot/factory_girl/wiki/Usage for more info)

    However this isn’t always great in Rails.env.development…

    Over time I have found that this is not actually the most useful way to create unique email addresses. The reason is that while the factory is always unique for your test environment it’s not always unique for your development environment and n resets itself as you start the environment up and down. In :test this isn’t a problem because the database is wiped but in :development you tend to keep the same data for a while.

    You then get collisions and find yourself having to manually override the email to something you know is unique which is annoying.

    Often more useful: use a random number

    Since I call u = Factory :user from the console on a regular basis I go instead with generating a random number. You’re not guaranteed to avoid collisions but in practice it hardly ever happens:

    Factory.define :user do |user|
      user.email {"user_#{Random.rand(100000000).to_s}@factory.com" }
      user.password{ "secret" }
    end
    

    N.B. You have to use Random.rand rather than rand() because of a collision (bug?) in FactoryGirl [https://github.com/thoughtbot/factory_girl/issues/219](see here).

    This frees you to create users at will from the command line regardless of whether there are already factory generated users in the database.

    Optional extra for making email testing easier

    When you get into email testing you often want to verify that an action by a particular user triggered an email to another user.

    You log in as Robin Hood, send an email to Maid Marion and then go to your inbox to verify it. What you see in your inbox is something from user_842@factory.com. Who the hell is that?

    You need to go back to your database to check whether the email was sent / received by whomever you expected it to be. Again this is a bit of a pain.

    What I like to do instead is to generate the email using the name of the Factory user combined with a random number. This makes it far easier to check who things are coming from (and also makes collisions vanishingly unlikely). Using the Faker gem (http://faker.rubyforge.org/) to create the names we get:

    Factory.define :user do |user|
      user.first_name { Faker::Name::first_name }
      user.last_name { Faker::Name::last_name }
      user.email {|u| "#{u.first_name}_#{u.last_name}_#{Random.rand(1000).to_s}@factory.com" }
    end
    

    finally, since Faker sometimes generates names that aren’t email-friendly (Mike O’Donnell) we need to whitelist acceptable characters: .gsub(/[^a-zA-Z1-10]/, '')

    Factory.define :user do |user|
      user.first_name { Faker::Name::first_name }
      user.last_name { Faker::Name::last_name }
      user.email {|u| "#{u.first_name.gsub(/[^a-zA-Z1-10]/, '')}_#{u.last_name.gsub(/[^a-zA-Z1-10]/, '')}_#{Random.rand(1000).to_s}@factory.com" }
    end
    

    This gives us personable but unique emails such as robin_hood_341@factory.com and maid_marion_10@factory.com

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Suppose I have the following models: class User(models.Model): pass class A(models.Model): user = models.ForeignKey(User)
Suppose you have two models, User and City, joined by a third model CityPermission:
Suppose I have class Foo(db.Model): bar = db.ReferenceProperty(Bar) foo = Foo.all().get() Is there a
Suppose I have 2 models. The 2nd model has a one-to-one relationship with the
I have a model Client which has many :tours, association in it. I am
I have a user model in which I have a method for seeing if
Suppose I have an Account model which has_many Users. Accounts have a boolean active
For example: I have a User which has 10 Widgets. Along with that I
My rails app has a simple model Links which tracks all the Urls associated
I have a model named UserPrice which has a form where you can create

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.