ruby-on-railstestingvalidates-uniqueness-of

I am trying to use case sensitive uniqueness on rails and the test is failing


I am currently following a Michael Hartl tutorial on ruby on rails. Every time I run a model:test it fails due to the emails uniqueness. Even though I have stated that in the model. I want to fix this before I start adding data to the web application.

This is my user.rb

before_save { self.email = email.downcase! }
validates :name, presence: true, length: { maximum: 50 }

# Regex explaination below
# / :   start of regex | \A : match start of a string
# [\w+\-.]+ : at least one word character, plus, hyphen, or dot
# @ : literal “at sign” | [a-z\d\-.]+ : at least one letter, digit, hyphen, 
or dot
# \. : literal dot | [a-z]+ : at least one letter
# \z : match end of string | / : end of regex
# i :  case-insensitive
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
                uniqueness: { case_sensitive: false },
                format: { with: VALID_EMAIL_REGEX }

This is my user_test.rb

test "email addresses should be unique" do
  duplicate_user = @user.dup
  duplicate_user.email = @user.email.upcase
  @user.save
  assert_not duplicate_user.valid?
end

Solution

  • Before your assertion call duplicate_user.save. That will trigger the validations on that model.