Search code examples
rubyautomated-testsconditional-statementshttparty

Case conditional in ruby doesn't enter in when


My code when executed it's not entering in the when loop inside the case conditional. What I wanted is to sen two different GET requests based on the *args of the function. So I can validate the errors when I don't send one of the parameters in the request. If someone have a better logic to do it one method, I appreaciate as well.

Here is my code:

def get_function(access_token,order1,order2,*args)
    case args
      when  args = "order1"
        self.class.get("/v1/apiendpoint?order2=#{order2}",
                   headers: {'accesstoken': "#{access_token}"})
      when args = "order2"
        self.class.get("/v1/apiendpoint?order1=#{order1}",
                   headers: {'accesstoken': "#{access_token}"})
    end
  end

When I execute with binding.pry (debugging) it shows this part, and doesn't execute the rest of the code.

From: C:/Ruby26-x64/lib/ruby/gems/2.6.0/gems/cucumber-core-8.0.1/lib/cucumber/core/test/action.rb @ line 25 Cucumber::Core::Test::Action#execute:

22: def execute(*args)
23:   @timer.start
24:   @block.call(*args)
==> 25:   passed
26: rescue Result::Raisable => exception
27:   exception.with_duration(@timer.duration)
28: rescue Exception => exception
29:   failed(exception)
30: end

Solution

  • There are multiple problems here:

    case args
    when  args = "order1"
    

    Firstly, args is an Array - so it cannot possibly be equal to a String. I'm not sure what you intended to happen here, so can't say exactly how to fix it.

    Secondly, = is an assignment operator, whereas == performs an equality check.

    And lastly, this is a case statement, not an if statement, so you shouldn't actually be performing an equality check here... Either of these would have made sense syntactically:

    case args
    when "order1"
       # ...
    end
    
    # OR:
    
    case
    when args == "order1"
      # ...
    end
    

    Also, note that your question description is a bit confusing. You said:

    the when loop

    but this is not a loop. You could call it a "clause", or a "statement", but it's certainly not a "loop".