user1097108
user1097108

Reputation: 355

How to exit out of Ruby Cucumber Step definition early?

I don't know why this is so difficult. I've tried several things, but for some reason this Ruby Cucumber code either continues onto the next code in the block, or I get something like "unexpected return (LocalJumpError)". Is this something obvious that I can't find the answer to?

I have a workaround by just wrapping all the code in an "if condition == false", but is there a better way?

When(/^I create scenarios$/) do
   if condition == true
     #exit, return, next, break ????
   end
   #code i don't want to execute if condition matches
end

Upvotes: 4

Views: 1217

Answers (3)

Ben Behar
Ben Behar

Reputation: 364

I believe that you are looking to exit the block early by using 'next'.

next if condition

Upvotes: 8

Andrew B
Andrew B

Reputation: 104

Because you want nothing to happen if the condition is true, I would recommend using unless in the step definition.

When(/^I create scenarios$/) do
  unless condition == true
     #code you want to execute when the condition is false
  end
end

If condition == true, the flow will just move on to the next step.

Upvotes: -1

Mayshar
Mayshar

Reputation: 190

The issue your having with the code sample you have given is that the code you don't want to execute isn't part of your if block.

What happens the way you have written it, is it will check the if condition, then execute based on what it finds. Then, it moves to the next line of code, which is your code you don't want to run.

My suggestion, is to try something like this,

When(/^I create scenarios$/) do
   if condition == true
   else
     #code i don't want to execute if condition matches
   end
end

What will happen here, is it will check the if condition, and if it is true, the code will do nothing but SKIP the else step because it met the if condition. When it checks the if condition, if it comes back false, then it will move on to the else step, and execute that code.

I cant promise this is the BEST way to write this code, but this is simple and should suffice to solve the problem

Upvotes: 0

Related Questions