【发布时间】:2014-12-01 23:54:30
【问题描述】:
我有一个自定义验证方法,它使用正则表达式匹配用户输入,如果失败则抛出错误。
我试图理解为什么以下场景通过但第二个示例抛出
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(引发错误)
# 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
任何关于为什么第二次失败的指针将不胜感激,我将如何让该测试通过
谢谢
编辑
所以如果提供了 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 为 nil 的测试仍然失败
如果没有 mobile_no 没有输入,则查看参数,它被传递为“mobile_no”=>“”,尽管它仍然是 nil 不是吗?
【问题讨论】:
-
作为一个附带问题,您问'查看参数,如果没有 mobile_no 没有输入,它被传递为 "mobile_no"=>"",尽管它仍然是 nil 不是吗?不,空字符串不是零。但是,您是对的,空字符串与正则表达式不匹配,所以我很困惑为什么 japed 的答案对您不起作用。
标签: ruby-on-rails ruby regex ruby-on-rails-4 rspec