2014-10-07 39 views
0

我有一個自定義的驗證方法,使用正則表達式匹配用戶輸入,然後拋出一個錯誤,如果失敗。自定義驗證方法和rspec測試

進出口試圖理解爲什麼以下情形通過但第二示例引發

undefined method match 

實施例1(通過)

# Custom Validation 
def format_mobile 
regexp = "/^(07[\d]{9})$/" 
    if !(mobile_no.match(regexp)) 
    errors[:base] << "Please check your Mobile Number" 
    end 
end 

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

實施例2(引發Error)

# Custom Validation 
def format_mobile 
regexp = "/^(07[\d]{9})$/" 
    if !(mobile_no.match(regexp)) 
    errors[:base] << "Please check your Mobile Number" 
    end 
end 

# rspec test 
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 check your Mobile Number") 
end 

任何關於爲什麼第二次失敗的指針將不勝感激,並且我將如何得到那te ST通

感謝

編輯

所以這將通過測試,如果說mobile_no 07805362669是提供

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

但如果mobile_no是測試爲零仍未

看看params如果沒有mobile_no沒有輸入它通過「mobile_no」=>「」,這仍然是零雖然不是嗎?

+0

作爲一個方面的問題的另一種方式,你問「看PARAMS如果沒有mobile_no沒有輸入它作爲‘mobile_no’=>‘’過去了,這仍然是零,雖然心不是它?'不,空字符串不是零。然而,你說得對,空字符串與正則表達式不匹配,所以我很困惑爲什麼japed的答案不適合你。 – dcorking 2014-10-07 14:51:09

回答

2

nil實現在紅寶石零類不具有匹配方法。

String確實有匹配方法。

regexp一樣,您將字符串傳遞給正則表達式。因此,簡單地把它周圍

if !(regexp.match(mobile_no)) 
    #do_whatever 
end 
+0

正如itsnikolay指出,你已經使你的正則表達式包裝它在引號中。 – 2014-10-07 14:23:53

+0

似乎你的答案是正確的(當我想到它時有意義)認爲我的正則表達式有問題,如果我提供了12位數字,測試通過,但如果我提供10位數字,則失敗,我希望它失敗10以及 – Richlewis 2014-10-07 15:11:31

+0

@Richlewis我推薦[rubular](http://rubular.com) – 2014-10-07 15:16:32

1

這應該解決您的問題
我已經刪除""$
現在應該通過

def format_mobile 
regexp = /^(07[\d]{9})/ 
    unless mobile_no.match(regexp) 
    errors[:base] << "Please check your Mobile Number" 
    end 
end 

rspec的:

let(:user) { build :user, mobile_no: '07000000000' } 
it 'validates mobile number' do 
    expect(user.valid?).to be_falsey 
    expect(user.errors).to include 'format errror message' 
end 

全面實施驗證的正則表達式與 https://gist.github.com/itsNikolay/7bc0b946770da4bf039a

,但更好的驗證與

validates :mobile_no, presence: true, format: { 
    with: /^(07[\d]{9})/, 
    message: 'shoud be in US format' 
} 
+0

謝謝...更新了我的語法錯誤,但仍然得到相同的行爲 – Richlewis 2014-10-07 14:14:49

+0

@Richlewis我已經更新了我的答案 – itsnikolay 2014-10-07 14:23:26

+0

謝謝,我不得不這樣做,但它使工作,除非regexp.match(mobile_no)...我刪除「」和$ aswell ..但在mobile_no爲零的情況下,我如何獲得該通行證?在我的方法中添加額外的條件? – Richlewis 2014-10-07 14:33:16