2014-10-08 57 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

相关问题