2016-08-20 2 views
1

電話番号の値が「+48 999 888 777 \ naseasd」に等しい最後のテストに正規表現を書き込む問題があります。ここに私のファイルがあります。私は間違っているの?改行文字でこの電話番号を許可しないようにRegexを書くには?

アプリ/モデル/ 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 

仕様/モデル/ 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 

コンソールでのエラーは次のとおりです。

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)>' 
+0

冒頭に '\ A 'を、パターンの最後に' \ z'を追加します。 –

+0

ありがとう!それは今働いている。ここで私はそれについてのより多くの情報を見つけました:[Ruby正規表現の\ A \ zと^ $の違い](http://stackoverflow.com/questions/577653/difference-between-az-and-in-ruby-regular-式)。私は以前の^ $を使用していました。 –

答えて

0

あなた

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

は、パターン全体を文字列に一致させることを意味します。

先頭に\Aを追加し、パターンの最後に\zを追加します。

^は、Rubyの行の先頭に一致します($は行の最後に一致します)。通常、RoRでは例外が発生します。 \zのアンカーは、\Zが文字列の最後の改行の前に一致し、\zが文字列の最後にのみ一致するため、検証の目的で\Zよりも優れています。

関連する問題