【问题标题】:custom validation method and rspec tests自定义验证方法和 rspec 测试
【发布时间】: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


【解决方案1】:

nil 是 ruby​​ 中的一个 nil 类,没有匹配方法。

String 确实有匹配方法。

就像regexp 一样,您将字符串传递给正则表达式。所以简单地把它称为​​相反的方式

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

【讨论】:

  • 正如 itsnikolay 指出的那样,您已经通过将正则表达式括在引号中来使其成为字符串。
  • 似乎你的答案是正确的(当我想到它时有道理)认为我的正则表达式有问题,如果我提供 12 位数字,测试通过,但如果我提供 10 则失败,我希望它也以 10 失败
【解决方案2】:

这应该可以解决您的问题
我已删除 ""$
现在应该可以通过了

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'
}

【讨论】:

  • 谢谢...更新了我的语法错误,但仍然得到相同的行为
  • 谢谢,我必须这样做才能让它工作,除非 regexp.match(mobile_no)...我能通过吗?在我的方法中添加额外的条件?
  • @Richlewis 我附上了验证的 git 实现
  • @Richlewis 允许用户不提供手机号码?还是手机号码应该一直显示?
  • 感谢您的帮助,认为现在解决了,我的正则表达式有问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多