In cucumber, you often want to be able to use a step in both it’s positive and negative form. For example, in different universes I might want to ensure that “pigs can fly”, or that “pigs can not fly”. Typically I’ve either written two step matchers for this, or added an awkward conditional:
Then /^pigs can (not |)fly$/ do |negated| if negated.blank? Pig.new.should have_the_power_of_flight else Pig.new.should_not have_the_power_of_flight end end
But today I decided to factor that out into a little helper method in my cucumber config:
# features/support/env.rb class Object def should_unless(missing, matcher) missing.match(/not/) ? should_not(matcher) : should(matcher) end end
This allows me to write my matcher much more simply:
Then /^pigs can (not |)fly$/ do |negated| Pig.new.should_unless negated, have_the_power_of_flight end
So fresh and so DRY!