Hey,

I just ran into a situation where I would like to expect a method call
with an argument I know and another one, which is a random number. I
think mocking up the rand method is somehow ugly so I thought maybe
this is the first time where I can take something from Java to Ruby ;)
Java's EasyMock mocking library knows things like "anyObject()" and
"anyInteger()" in their method equivalent  to should_receive. I like
the idea so I added this to my Rails spec_helper.rb:

class AnyObjectComparator
 attr_reader :object
 def ==(other)
   @object = other
   true
 end
end

class AnyNumberComparator <  AnyObjectComparator
 def ==(other)
   super.==(other)
   other.is_a?(Numeric)
 end
end

def any_object
 @any_object ||= AnyObjectComparator.new
 @any_object
end

def any_number
 @any_number ||= AnyNumberComparator.new
 @any_number
end

Which gives me the ability to do the should_receive call like this:

 Item.should_receive(:random_item).with(any_object,
any_number).at_least(1).times.and_return(mock_model(Item))

(the first any_object parameter is only in there for demonstration purposes ;) )
And if I would like to it's possible to get the actual value which was
passed to as an argument with: any_xxx.object
Ok, these any_xxx things behave somehow like a singleton but it's no
problem at all to instantiate more of them to use many of them and
afterwards get the actual value of any of them.

So long. My question is: Is this too much effort? Is something like
this already built into RSpec, I can't find something but I can't
believe there isn't ;) and could this be done smarter? This singleton
like behavior of any_xxx feels grubby.

Thank you a lot!

Thorben
_______________________________________________
rspec-users mailing list
rspec-users@rubyforge.org
http://rubyforge.org/mailman/listinfo/rspec-users

Reply via email to