Sohan's Blog

Living the Developer's Life

Random Data in Tests

… are evil if you expect the randomizer to give you unique values on each call.

Here’s an example:

1
2
3
4
5
6
7
before(:each) do
  @user_1 = User.create!(email: "email-#{Random.rand(1000)}@example.com")

  # the following will fail intermittently if you have a unique validation on User#email

  @user_2 = User.create!(email: "email-#{Random.rand(1000)}@example.com")
end

It’s a timebomb, use it, it will haunt you later. Be sane, stop using random numbers in tests like this.

Comments