首页 > 解决方案 > ruby中的条件条件不输入when

问题描述

我的代码在执行时没有进入 case 条件内的 when 循环。我想要的是根据函数的 *args 发送两个不同的 GET 请求。因此,当我不发送请求中的参数之一时,我可以验证错误。如果有人有更好的逻辑来做一种方法,我也很感激。

这是我的代码:

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

当我使用 binding.pry(调试)执行时,它会显示这部分,并且不执行其余代码。

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

标签: rubyautomated-testsconditional-statementshttparty

解决方案


这里有多个问题:

case args
when  args = "order1"

首先,argsis an Array- 所以它不可能等于 a String。我不确定你打算在这里发生什么,所以不能准确地说出如何解决它。

其次,=赋值运算符,而==执行相等性检查。

最后,这是一个case语句,而不是一个if语句,所以你实际上不应该在这里执行相等性检查......这些中的任何一个在语法上都是有意义的:

case args
when "order1"
   # ...
end

# OR:

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

另外,请注意您的问题描述有点混乱。你说:

当循环

但这不是一个循环。您可以将其称为“子句”或“语句”,但它肯定不是“循环”。


推荐阅读