Posted about 9 years ago. Visible to the public.

# Test that a number or money amount is shown with Cucumber

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

```Copy```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:

```Copy```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:

```Copy```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!

```Copy```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}|&nbsp;)(#{unit}|#{Regexp.quote(HTMLEntities.new.encode(unit, :named))})" :"\\b"))
expectation = negate ? :should_not : :should
page.body.send(expectation, match(regexp))
end
``````

## Webrat

```Copy```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}|&nbsp;)(#{unit}|#{Regexp.quote(HTMLEntities.new.encode(unit, :named))})" :"\\b"))
expectation = negate ? :should_not : :should
response.body.send(expectation, match(regexp))
end
``````

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Last edit:
over 4 years ago
by Henning Koch