如何从Ruby中的Mocha模型返回动态值

Viv*_*vek 14 ruby mocking mocha.js

我的问题的要点如下: -

我正在Ruby中编写一个Mocha模拟器,用于下面表示为"post_to_embassy"的方法.出于描述问题的目的,实际方法的作用并不是我们真正关心的问题.但是我需要模拟来返回一个动态值.下面的proc'&prc'正在代替实际方法正确执行.但是Mocha中的"with"方法只允许返回布尔值.所以下面的代码输出nil.我需要它来输出通过orderInfoXml传递的值.有谁知道我可以使用的替代方法?

require 'rubygems'
require 'mocha'
include Mocha::API

class EmbassyInterface 
  def post_to_embassy(xml)
    puts "This is from the original class:-"
    puts xml
    return xml
  end
end

orderInfoXml = "I am THE XML"

mock = EmbassyInterface.new
prc = Proc.new do |orderXml| 
  puts "This is from the mocked proc:-"
  puts orderXml
  orderXml
end

mock.stubs(:post_to_embassy).with(&prc)
mock_result = mock.post_to_embassy(orderInfoXml)
p mock_result
#p prc.call("asd")
Run Code Online (Sandbox Code Playgroud)

输出: -

This is from the mocked proc:-
I am THE XML
nil
Run Code Online (Sandbox Code Playgroud)

now*_*owk 5

我不确定是否有一个完美的方法.但是为了让生活更轻松,而不是将每个可能的响应(如另一个答案所述),你可以使用Mocha的yields方法.

require "rubygems"
require "mocha"

include Mocha::API

class EmbassyInterface

  def post_to_embassy(xml)
    puts "This is form the original class:-"
    puts xml
    xml
  end
end

order_info_xml = "I am the xml"

mock = EmbassyInterface.new

prc = Proc.new do |order_xml|
  puts "This is from the mocked proc:-"
  puts order_xml
  order_xml
end

mock.stubs(:post_to_embassy).yields prc

prc_return = nil

mock.post_to_embassy { |value| prc_return = value.call("hello world") }
puts prc_return

mock.post_to_embassy { |value| prc_return = value.call("foo") }
puts prc_return
Run Code Online (Sandbox Code Playgroud)

输出:

This is from the mocked proc:-
hello world
hello world

This is from the mocked proc:-
foo
foo
Run Code Online (Sandbox Code Playgroud)

这将要求您分配prc的返回值,并且它不完全漂亮(imo).但是,你不必剔除每一个期望,这会给你很大的自由.

  • 这不是Expectation#yield的预期用途.我不推荐这种技术. (3认同)

met*_*ida 0

我还没有找到一种方法使模拟方法的输出完全动态,但如果您的输入数量有限且已知,则可以使输出正常工作。

require 'rubygems'
require 'mocha'
include Mocha::API

class EmbassyInterface 
  def post_to_embassy(xml)
    "original: #{xml}"
  end
end

to_mock = EmbassyInterface.new
orderInfoXml1 = "I am the first XML."
orderInfoXml2 = "I am the second XML."

p to_mock.post_to_embassy(orderInfoXml1)

prc = Proc.new do |xml| 
  "mocked: #{xml}"
end
to_mock.stubs(:post_to_embassy).with(orderInfoXml1).returns(prc.call(orderInfoXml1))
to_mock.stubs(:post_to_embassy).with(orderInfoXml2).returns(prc.call(orderInfoXml2))

p to_mock.post_to_embassy(orderInfoXml1)
p to_mock.post_to_embassy(orderInfoXml2)
p to_mock.post_to_embassy(orderInfoXml1)
Run Code Online (Sandbox Code Playgroud)

输出:

"original: I am the first XML."
"mocked: I am the first XML."
"mocked: I am the second XML."
"mocked: I am the first XML."
Run Code Online (Sandbox Code Playgroud)