Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec: How to test that substring appears in string a certain amount of times?

Trying to use the .exactly method but it doesn't seem to work here.

expect(data).to include(purchase.email).exactly(3).times

This produces the error:

 NoMethodError:
   undefined method `exactly' for #<RSpec::Matchers::BuiltIn::Include:0x007f85c7e71108>
 # ./spec/models/csv_generator_spec.rb:34:in `block (4 levels) in <top (required)>'
 # ./spec/models/csv_generator_spec.rb:18:in `each'
 # ./spec/models/csv_generator_spec.rb:18:in `block (3 levels) in <top (required)>'

Does anyone know how I would test that a substring appears a certain amount of times in a string?

like image 297
bigpotato Avatar asked May 12 '14 21:05

bigpotato


1 Answers

You can use the scan method, which returns an array of matches. Then you just check the size of the array:

expect(data.scan(purchase.email).size).to eq(3)

An alternative is this syntax:

expect(data.scan(purchase.email)).to have(3).items

expect(data.scan(purchase.email)).to have_exactly(3).items
like image 114
fivedigit Avatar answered Oct 27 '22 14:10

fivedigit