Ruby on rails rspec中的Rails正则表达式验证失败
我正在尝试编写和测试一个正则表达式有效性,它只允许一个成对整数序列,格式为Ruby on rails rspec中的Rails正则表达式验证失败,ruby-on-rails,regex,rspec,Ruby On Rails,Regex,Rspec,我正在尝试编写和测试一个正则表达式有效性,它只允许一个成对整数序列,格式为 n,n n,n 其中n是任何不以零开始的整数,并且对是空格分隔的。可能只有一对,或者字段也可能为空 因此,对于这些数据,它应该给出2个错误 12,2 11,2 aa 111,11,11 错误1:“aa” 错误2:三元组(111,11,11) 在我的Rails模型中,我有这个 validates_format_of :sequence_excluded_region, :sequence_included_reg
n,n n,n
其中n是任何不以零开始的整数,并且对是空格分隔的。可能只有一对,或者字段也可能为空
因此,对于这些数据,它应该给出2个错误
12,2 11,2 aa 111,11,11
- 错误1:“aa”
- 错误2:三元组(111,11,11)
validates_format_of :sequence_excluded_region, :sequence_included_region,
with: /[0-9]*,[0-9] /, allow_blank: true
it 'is invalid with alphanumeric SEQUENCE_INCLUDED_REGION' do
expect(DesignSetting.create!(sequence_included_region: '12,2 11,2 aa 111,11,11')).to have(1).errors_on(:sequence_included_region)
end
在我的Rspec模型测试中,我有
validates_format_of :sequence_excluded_region, :sequence_included_region,
with: /[0-9]*,[0-9] /, allow_blank: true
it 'is invalid with alphanumeric SEQUENCE_INCLUDED_REGION' do
expect(DesignSetting.create!(sequence_included_region: '12,2 11,2 aa 111,11,11')).to have(1).errors_on(:sequence_included_region)
end
测试失败,因为正则表达式找不到错误,或者我调用的测试不正确
Failures:
1) DesignSetting is invalid with alphanumeric SEQUENCE_INCLUDED_REGION
Failure/Error: expect(DesignSetting.create!(sequence_included_region: '12,2 11,2 aa 111,11,11')).to have(2).errors_on(:sequence_included_region)
expected 2 errors on :sequence_included_region, got 0
# ./spec/models/design_setting_spec.rb:5:in `block (2 levels) in <top (required)>'
故障:
1) 设计设置无效,包含字母数字序列\u\u区域
失败/错误:期望(DesignSetting.create!(包含序列的区域:'12,2 11,2 aa 111,11,11'))上有(2).错误(:包含序列的区域)
上应出现2个错误:序列\u包含\u区域,得到0
#./spec/models/design\u setting\u spec.rb:5:in'block(2层)in'
(?Regex
正则表达式匹配一对,后跟字符串中任意一个空格
'12,2 11,2 aa 111,11,11 13,3'.scan /[0-9]*,[0-9] /
=> ["12,2 ", "11,2 "]
因此,任何一对有效的字符串后跟一个空格都是有效的。而且,由于没有空格,单个对将失败3,4
验证整个字符串的正则表达式:
positive_int = /[1-9][0-9]*/
pair = /#{positive_int},#{positive_int}/
re_validate = /
\A # Start of string
#{pair} # Must have one number pair.
(?:\s#{pair})* # Can be followed by any number of pairs with a space delimiter
\z # End of string (no newline)
/x
验证器
我不太使用rails,但似乎您对一个简单的正则表达式验证器的期望太高了,它无法为您从字符串中解析出单个错误组件
如果按空间分割变量,然后验证数组的每个元素,则可以获得每个字段的详细信息
'12,2 11,2 aa 111,11,11 13,3'.split(' ').reject{|f| f =~ /^[1-9][0-9]*,[1-9][0-9]*$/ }
您可以将类似的内容放入自定义验证器类中,然后使用该类可以直接控制您的
class RegionValidator record.errors[sequence\u included\u region]正则表达式正在工作,但旧的正则表达式也在工作。这可能是Rspec的问题。