Read more

Test that a number or money amount is shown with Cucumber

Henning Koch
May 25, 2011Software engineer at makandra GmbH

This is an awful way to test whether a number is shown on the screen:

Then I should see "5"
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

It is awful because the step above is green for 5, 5123 and -51.

This step definition below makes sure this doesn't happen. You can use it like this:

Then I should see the number 5

The step also works if you you'd like to test that the number is followed by a unit:

Then I should see the amount 5 €

The separator between the number and its unit is allowed to be either a space or a nbsp.

The step definitions require the htmlentities gem.

Capybara

This step is part of Spreewald Show archive.org snapshot !

Then /^I should( not)? see the (?:number|amount) ([\-\d,\.]+)(?: (.*?))?$/ do |negate, amount, unit|
  no_minus = amount.starts_with?('-') ? '' : '[^\\-]'
  nbsp = 0xC2.chr + 0xA0.chr
  regexp = Regexp.new(no_minus + "\\b" + Regexp.quote(amount) + (unit ? "( |#{nbsp}| )(#{unit}|#{Regexp.quote(HTMLEntities.new.encode(unit, :named))})" :"\\b"))
  expectation = negate ? :should_not : :should
  page.body.send(expectation, match(regexp))
end

Webrat

Then /^I should( not)? see the (?:number|amount) ([\-\d,\.]+)(?: (.*?))?$/ do |negate, amount, unit|
  no_minus = amount.starts_with?('-') ? '' : '[^\\-]'
  nbsp = 0xC2.chr + 0xA0.chr
  regexp = Regexp.new(no_minus + "\\b" + Regexp.quote(amount) + (unit ? "( |#{nbsp}| )(#{unit}|#{Regexp.quote(HTMLEntities.new.encode(unit, :named))})" :"\\b"))
  expectation = negate ? :should_not : :should
  response.body.send(expectation, match(regexp))
end
Posted by Henning Koch to makandra dev (2011-05-25 13:03)