2016-08-20 66 views
1

我有問題寫正則表達式通過最後一次測試,電話號碼值等於「+48 999 888 777 \ naseasd」。這是我的文件。我做錯了什麼?如何寫正則表達式不允許這個電話號碼換行符?

應用程序/模型/ 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要好。

相關問題