Adding stubs for an included argument

Hi,

My scenario is as follows, and so far I have not found the clean way
to implement the following.

In a method I have a method called allowed_for?(*args) used as
follows:

if o.allowed_for?(:foo, :bar)
#case a
elsif o.allowed_for(:quux, :bif)
#case b
elsif o.allowed_for(:baz)
#case c
else
#case default
end

now in the spec, I’d like to say something like

obj.should_allow_for(:foo)
obj.stub!(:allowed_for? => false)

that is, if allowed_for? is called with varargs containing :foo it
should return true, false otherwise.

At the moment the only way I can make the spec to run is to create
exact expectation, which is a bit too tightly coupled to the
implementation:

obj.should_receive(:allowed_for?).with(:foo, :bar).and_return …

another solution would wrap allow_for?(*args) into a single method
call without parameter names and stubbing the wrapper methods:

if o.fooey?
#case a
elsif o.quuxy?
#case b
elsif o.bazy?
#case c
else
#case default
end

but I don’t like it - the rules are simple and the whole method is now
quite readable as it is. Creating one-line private methods would IMO
add superfluous cruft and reduce legibility.

On Tue, Jan 5, 2010 at 4:09 AM, Edvard M.
[email protected]wrote:

if o.allowed_for?(:foo, :bar)
now in the spec, I’d like to say something like

obj.should_allow_for(:foo)
obj.stub!(:allowed_for? => false)

Try this:

obj.stub(:allowed_for) {|*args| args.include?(:foo)}

HTH,
David

Woohoo! I was aware of the block construct, but didn’t know it worked
with stub! as well (with should_receive, I had to use at_least… and
it broke the system, making it unusable).

Thanks!