user3007294
user3007294

Reputation: 951

Rspec Test for Regular Expression

*I am still very new to testing

Code (simply returns a number if it's three digits or less)

File name: example.rb

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

Rspec

File name: 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

Whenever I run this, I get the error:

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

Any suggestions? I believe something is wrong with the regular expression, so I tried match(/\d{13}/) and that failed too.

Upvotes: 2

Views: 2981

Answers (1)

Paul Fioravanti
Paul Fioravanti

Reputation: 16793

Not sure about the require-related error, but you're trying to run a match-matcher for your regex against a Fixnum (the return value from your call to Kernel#rand), rather than a String:

irb(main)> "111".match(/^\d{1,3}$/)
=> #<MatchData "111">
irb(main)> 111.match(/^\d{1,3}$/)
NoMethodError: undefined method `match' for 111:Fixnum

So, I got your code to work with the following changes (I assumed the str_array_length was the length of the passed in number as a string):

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

Upvotes: 4

Related Questions