Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a dynamic value from a Mocha mock in Ruby

The gist of my problem is as follows:-

I'm writing a Mocha mock in Ruby for the method represented as "post_to_embassy" below. It is not really our concern, for the purpose of describing the problem, what the actual method does. But I need the mock to return a dynamic value. The proc '&prc' below is executing rightly in place of the actual method. But the "with" method in Mocha only allows for boolean values to be returned. So the code below outputs nil. I need it to output the value being passed through orderInfoXml. Does anyone know of an alternate method I can use?

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")

output:-

This is from the mocked proc:-
I am THE XML
nil
like image 353
Vivek Avatar asked Apr 30 '10 05:04

Vivek


1 Answers

I'm not sure if there is a perfect method for this. But to make life easier, than to stubbing each possible response (as described in another answer), you could go with Mocha's yields method.

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

outputs:

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

This is from the mocked proc:-
foo
foo

This will require you to assign the return of your prc, and it's not exactly pretty (imo). But, you don't have to stub out each expectation, which will give you quite a bit of freedom.

like image 149
nowk Avatar answered Sep 30 '22 03:09

nowk