Forums | Admin

Discussion Forums: help

Start New Thread Start New Thread

 

By: Brian Candler
Using a proc to set return values [ reply ]  
2008-06-26 14:00
Hi,

I'm not sure if I'm being dense here, or if this is a feature missing from mocha. I would like to be able to stub a method and have the return value chosen dynamically by calling a proc: e.g.

foo.stubs(:get).returns { |key| MAP[key] }

In flexmock the corresponding feature is "and_return { ... }".

This feature could also useful for side-effects from the proc, e.g.

buf = ""
foo.stubs(:puts).returns { |s| buf << s << "\n"; nil }
...
assert_equal("Line one\nLine two\n", buf)

For this I've been able to do it using "with":

foo.stubs(:puts).with { |s| buf << s << "\n"; true }

However here the block is constrained to return true, so AFAICS you can still only return static values from the stub.

Am I missing something obvious? I had a look through the code, and I wondered if something analagous to ExceptionRaiser would be needed (a "ProcCaller" perhaps?)

Thanks,

Brian.