Search code examples
ruby-on-railsregexrspecrspec-rails

How to write Regex to not allow this phone number with newline character?


I have problem to write regex to pass last test with phone number value equal "+48 999 888 777\naseasd". Here are my files. What I'm doing wrong?

app/models/user.rb

class User < ActiveRecord::Base

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
  :recoverable, :rememberable, :trackable, :validatable

  validates :phone_number, format: { with: /[+]?\d{2}(\s|-)\d{3}(\s|-)\d{3}(\s|-)\d{3}/, allow_nil: true }

end

spec/models/user_spec.rb

require 'rails_helper'

describe User do

  it { is_expected.to allow_value('+48 999 888 777').for(:phone_number) }
  it { is_expected.to allow_value('48 999-888-777').for(:phone_number) }
  it { is_expected.to allow_value('48 999-888-777').for(:phone_number) }
  it { is_expected.not_to allow_value('+48 aaa bbb ccc').for(:phone_number) }
  it { is_expected.not_to allow_value('aaa +48 aaa bbb ccc').for(:phone_number) }
  it { is_expected.not_to allow_value("+48 999 888 777\naseasd").for(:phone_number) }

end

Error in console is:

Failures:

1) User should not allow phone_number to be set to "+48 999 888 777\naseasd"
 Failure/Error: it { is_expected.not_to allow_value("+48 999 888 777\naseasd").for(:phone_number) }
   Expected errors  when phone_number is set to "+48 999 888 777\naseasd", got errors: ["can't be blank (attribute: \"email\", value: \"\")", "can't be blank (attribute: \"password\", value: nil)"]
 # ./spec/models/user_spec.rb:9:in `block (2 levels) in <top (required)>'

Solution

  • Your

    it { is_expected.not_to allow_value("+48 999 888 777\naseasd").for(:phone_number) }
    

    means you want your pattern to only match the entire string.

    Add \A at the beginning and \z at the end of the pattern.

    Note that ^ matches at the start of a line in Ruby (while $ matches at the end of the line), and in RoR usually cause an exception. The \z anchor is better than \Z for validation purposes since \Z can match before the final newline in the string and \z only matches at the very end of the string.