Apr 16 Cucumber step negating another expectation step
tags:
Cucumber is in the opinion of many a kick ass project, and no wonder given all it provides. I’ve being using it in several projects with great joy. Sometimes you need an expectation step to exactly negate another expectation step, generally is not clear what’s the meaning of negate an expectation step, but in boolean expectations it is easy to not them.
Let’s say you want to check whether some form exist in your page or not, you can do something like:
Then /^I (should|should not) see the people search form$/ do |maybe|
people_search_form_should_exist maybe == "should"
end
# and the method hides the complexity out of the step, and remain readable:
def people_search_form_should_exist it_should_exist
_not = "_not" unless it_should_exist
response.send "should#{_not}".to_sym, have_tag('form#frmSearch')
end
Matt Wynne suggested another approach more old_skool style that gave me the tips to mine, his is shorter and could even be faster, but I haven’t benchmark it though:
Then /^I (should|should not) see the people search form$/ do |maybe|
has_matching_tags = current_dom.css('form#frmSearch').length > 0
assert has_matching_tags == (maybe == "should")
end
update
wow! Matt make it even shorter:
Then /^I (should|should not) see the people search form$/ do |maybe|
response.send maybe.sub(' ','_').to_sym, have_tag('form#frmSearch')
end
which I turn into:
Then /^I (should|should not) see the people search form$/ do |maybe|
response.send should_or_not(maybe), have_tag('form#frmSearch')
end
# with the method
def should_or_not maybe
maybe.sub(' ', '_').to_sym
end
Update 2
There was also the non DRY but repeating solution, which I like:
Then /^the correspondence should (not )?have inclusions$/ do |negate|
if negate
@outcorr.inclusions.should be_empty
else
@outcorr.inclusions.should_not be_empty
end
end
but David Chelimski came up with a good one too:
Then /^I (should|should not) see the people search form$/ do
|should_or_should_not|
expect_that(response, should_or_should_not, have_tag('form#frmSearch'))
end
def expect_that(target, should_or_should_not, matcher)
target.send should_or_should_not.underscore.to_sym, matcher
end
well you pick yours