【问题标题】:how can I return 2 values from an Rspec Mock?如何从 Rspec Mock 返回 2 个值?
【发布时间】:2019-01-24 01:36:10
【问题描述】:

我正在尝试模拟Open3.capture2,我想返回一个字符串和一个双精度值作为状态。知道如何返回 2 值吗?

待测代码:

stdout, status = Open3.capture2(command)

if status.success?
  puts stdout
else
  puts stdout
  throw "error: could not execute"
end

规格:

it "throws an error" do
  status = double("status message", :success? => false)
  allow(Open3).to receive(:capture2).and_return("wat?", status)
  ScreenShotWorker.new.perform(url: "www.google.com")
  expect(Open3).to have_received(:capture2)
end

【问题讨论】:

    标签: ruby-on-rails ruby rspec ruby-on-rails-5


    【解决方案1】:

    你把它作为一个数组返回:

    allow(Open3).to receive(:capture2).and_return(["wat?", status])
    

    因此您可以将代码可视化为正在运行(状态值为“200”):

    stdout, status = ["wat", "200"]
    stdout #=> "wat"
    status #=> "200"
    

    这就是 ruby​​ 中多重赋值的工作原理——一个方法只能返回一个值,但如果它是一个数组,那么你可以使用多重赋值。

    【讨论】:

    • 完美。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 2015-06-19
    • 1970-01-01
    相关资源
    最近更新 更多