Rspec测试正则表达式

时间:2016-03-14 21:42:43

标签: ruby regex rspec

*我仍然很擅长测试

代码(如果数字为三位数或更少,则只返回一个数字)

文件名:example.rb

def separate_comma(number)
  str_array_length <= 3 ? (return number) : (return false)
end

Rspec的

文件名:spec_example.rb

require_relative "example"
require 'rspec'

def random_num(min, max)
   rand(max - min + 1) + min
end

describe "separate_comma" do
   it "returns no comma, when the integer is smaller than 1000" do
     expect(separate_comma(random_num(0, 999))).to match(/^\d{1,3}$/)
   end
end

每当我运行它时,我都会收到错误:

./spec_example.rb:10:in `block (2 levels) in <top (required)>'

有什么建议吗?我认为正则表达式出了问题,所以我尝试了匹配(/ \ d {13} /),但也失败了。

1 个答案:

答案 0 :(得分:1)

不确定与require相关的错误,但是您尝试针对match运行Fixnum匹配正则表达式(来自您String的回复值{3}}),而不是irb(main)> "111".match(/^\d{1,3}$/) => #<MatchData "111"> irb(main)> 111.match(/^\d{1,3}$/) NoMethodError: undefined method `match' for 111:Fixnum

str_array_length

所以,我让你的代码使用了以下更改(我假设def separate_comma(number) number = number.to_s number.length <= 3 ? (return number) : (return false) end def random_num(min, max) rand(max - min + 1) + min end describe "separate_comma" do it "returns no comma, when the integer is smaller than 1000" do expect(separate_comma(random_num(0, 999))).to match(/\A\d{1,3}\z/) end end 是传入的数字长度为字符串):

re.sub("(.*,.*){6},(.*)","\\1\n\\2",some_content)