Test that a number or money amount is shown with Cucumber

Updated . Posted . Visible to the public.

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

Then I should see "5"

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
Henning Koch
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2011-05-25 11:03)