1

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)>'
Hubert Jakubiak
  • 853
  • 8
  • 19
  • Add `\A` at the beginning and `\z` at the end of the pattern. – Wiktor Stribiżew Aug 20 '16 at 09:32
  • Thanks! It's working now. Here I found more information about it: [Difference between \A \z and ^ $ in Ruby regular expressions](http://stackoverflow.com/questions/577653/difference-between-a-z-and-in-ruby-regular-expressions). I was using earlier ^ $. – Hubert Jakubiak Aug 20 '16 at 09:45

1 Answers1

0

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563