2014-10-08 35 views
0

我有一個自定義方法,檢查一個正則表達式的值,但我也想檢查一個零值,但我不知道如果我檢查第一個子句中的兩個實例,我需要取決於其是否爲零兩個不同的錯誤信息或只是不匹配檢查零值自定義方法

def format_mobile 
regexp = /^(07[\d]{9})$/ 
    if !(regexp.match(mobile_no)) 
    errors[:base] << "Please check your Mobile Number" 
elsif mobile_no.blank? // also tried mobile_no == nil 
    errors[:base] << "Please provide your Mobile Number" 
end 
end 

Rspec的測試

通行證

it 'is invalid with a Invalid mobile number (Company)' do 
    user = FactoryGirl.build(:user, company_form: true, mobile_no: '0780') 
    user.format_mobile 
    expect(user.errors[:base]).to include("Please check your Mobile Number") 
end 

失敗

it 'is invalid with a NIL mobile number (Company)' do 
user = FactoryGirl.build(:user, company_form: true, mobile_no: :nil) 
user.format_mobile 
expect(user.errors[:base]).to include("Please provide your Mobile Number") 
end 

任何人都可以點我在正確的方向和我的自定義方法,請..它可能是一些簡單的,但不能似乎弄明白

感謝

+0

它與此不同http://stackoverflow.com/q/26237973/3297613? – 2014-10-08 07:37:50

+0

,因爲我認爲解決方案是在那些答案中,但經過進一步測試,他們似乎並沒有工作 – Richlewis 2014-10-08 07:38:51

+0

然後問問答題者。 – 2014-10-08 07:39:56

回答

2

的問題是在你的檢查順序。 nil將不匹配正則表達式,這就是爲什麼你永遠不會進入第二個elsif。只需更改訂單:

def format_mobile 
regexp = /^(07[\d]{9})$/ 
if mobile_no.blank? # also tried mobile_no == nil 
    errors[:base] << "Please provide your Mobile Number" 
elsif !(regexp.match(mobile_no)) 
    errors[:base] << "Please check your Mobile Number" 
end 
end 

希望它有幫助。

+0

令人驚歎,謝謝你,只是在控制檯中測試了這一點,它的工作原理:-)我好像被nil值拋出 – Richlewis 2014-10-08 07:52:29

相關問題