Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cucumber: How to use the same regex in different transforms?

I have the following Transform:

Transform /^"([^"]+)" Phase$/ do |name|
  # Returns the phase named 'name',
  # or raises an exception if it doesn't exist
end

which works with step definition like this:

Then /("(?:[^"]+)" Phase) should do something/ do |phase|
  # Should fail if the specified phase doesn't exist
end

I have also the following step definition which uses the same "([^"]+)" Phase pattern:

Given /("([^"]+)" Phase) follows ("([^"]+)" Phase)/ do |pre, post|
  # Should create the specified phases 
end

Here I don't want the step definition to fail if the specified phases doesn't exist. I would like to create the phases instead.

I would like to create a Transform that will create the phase for me to DRY up the step definitions a bit, but I can't do so because I already have the Transform mentioned above which has exactly the same regexp.

Basically, I would like to create the phase if it is a Given step, and raise fail if it is not.

Any ideas?

like image 917
Misha Moroshko Avatar asked Jul 01 '12 13:07

Misha Moroshko


1 Answers

If the regexps are the same, then you don't really have an option to differentiate the behaviour. Determining whether or not you're in a Given step might be possible, but even if so, it would be some very well-hidden magic with the potential to surprise future readers and scenario authors...

The easiest, and most intention-revealing way to do this would be to explicitly state the nature of the Phrase in the step language, then you can have 2 clearly-separated transforms e.g.

EXISTING_PHASE = Transform /^existing Phase "([^"]+)"$/ do |phase|
    # raise error if it doesn't exist
end

UNEXISTING_PHASE = Transform /^unknown Phase "([^"]+)"$/ do |phase|
    # create the phase if it doesn't exist
end
like image 144
Jon M Avatar answered Nov 05 '22 09:11

Jon M