Question

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?

Était-ce utile?

La solution

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

Autres conseils

You could also do this using the repeated regex pattern like this,

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

Then, expect use regexp matcher in rspec as,

match = data.match(r)
expect(data).to match(r)
expect(match[1]).to be_eql(purchase.email)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top