Posted over 8 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}| )(#{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}| )(#{unit}|#{Regexp.quote(HTMLEntities.new.encode(unit, :named))})" :"\\b")) expectation = negate ? :should_not : :should response.body.send(expectation, match(regexp)) end
Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Avatar
Henning Koch
Last edit:
almost 4 years ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more