Rspec: How to check that a substring is displayed in a string a certain number of times?

Trying to use the .exactly method, but it does not work here.

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

This results in an 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 will test that a substring appears on a line several times?

+6
source share
2 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 
+7
source

You can also do this using a repeating regex pattern like

 r = %r{(#{purchase.email}).*\1.*\1.*} 

Then expect to use regexp matcher in rspec as,

 match = data.match(r) expect(data).to match(r) expect(match[1]).to be_eql(purchase.email) 
0
source

All Articles