自定义验证方法和 rspec 测试
我有一个自定义验证方法,它使用正则表达式来匹配用户输入,然后在失败时抛出错误.
I have a custom validation method that uses a regexp to match on a users input and then throw an error if it fails.
我试图理解为什么以下场景通过但第二个示例抛出
Im trying to understand why the following scenario passes but the second example throws
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
任何关于为什么第二个失败的指针将不胜感激,我将如何让该测试通过
Any pointers as to why the second fails would be greatly appreciated, and how would i get that test to pass
谢谢
编辑
所以如果说提供了 mobile_no 07805362669,这将通过测试
so this will pass a test if say the mobile_no 07805362669 was provided
def format_mobile
regexp = /^(07[\d]{9})/
if !(regexp.match(mobile_no))
errors[:base] << "Please check your Mobile Number"
end
end
但是 mobile_no 为 nil 的测试仍然失败
but the tests where mobile_no is nil still fail
查看参数,如果没有 mobile_no 没有输入,它会作为mobile_no"=>"传递,尽管不是吗?
looking at the params if no mobile_no has no input it is passed as "mobile_no"=>"", this is still nil though isnt it ?