[Chicago Area Ruby Group] Functor
chicagogroup-members-list at rubyforge.org
chicagogroup-members-list at rubyforge.org
Thu Oct 7 22:54:06 EDT 2004
chicagogroup-members-list at rubyforge.org wrote:
> Wow. Um, can you elaborate a bit on that, maybe with a little bit of
> code? I think I might see what you're driving at, but I'm not quite
> there.
Given the following definition of a Functor:
class Functor
def initialize(&func)
@func = func
end
def method_missing(op, *args)
@func.call(op, *args)
end
end
Pretend I have a method called redirect that I am trying to test:
def redirect(url, sys=Kernel)
#
# code here that writes out an HTTP header
# that causes the redirect to url
#
# my header has been written so kill the script:
sys.exit
end
Here's my test method:
def test_redirect__exit
exited = false
sys = Functor.new { |meth, *args|
exited = true if meth == :exit
}
redirect('test/url.html', sys)
assert(exited)
end
Normally I would have created my own mock object instead and defined the
test method like so:
def test_redirect__exit
sys = Object.new
def sys.exit
@exited = true
end
def sys.exited?
@exited || false
end
redirect('test/url.html', sys)
assert(sys.exited?)
end
Not nearly as clean. This example is admittedly contrived, but I think
it gives you an idea of how you could use a Functor as a Mock object.
I'm sure there are a ton of other uses, but this is what came to mind.
Pretty cool use of method missing.
--
John
More information about the ChicagoGroup-Members-List
mailing list