[mocha-developer] mocking missing methods

James Mead jamesmead44 at gmail.com
Mon Apr 30 14:04:47 EDT 2007


On 27/04/07, Jay Fields <jay at jayfields.com> wrote:
>
> How about:
>
> # instance methods
> sheep = mock
> sheep.restricted_to Sheep.instance_methods
>
> or
>
> # class methods
> sheep = mock
> sheep.restricted_to Sheep.singleton_methods
>
> It's a bit more verbose, but more readable in my opinion.  Also, I'm
> not sold on responds_to or restricted_to.  I don't find that either
> one conveys the intent I'm looking for.
>

I was suggesting "responds_like", not "responds_to" or "restricted_to".

I don't think the #instance_methods & #singleton_methods style is quite
right. e.g. what if #method_missing accepts method names matching a
particular pattern. In this case #respond_to? should return true for any
method names that #method_missing would handle, but there is no equivalent
requirement for #instance_methods to include all matching method names (in
fact this list could theoretically be infinite).

An obvious example of this would be ActiveRecord's find_by_xxx_and_yyy type
methods. It's not a great example, because when I last checked ActiveRecord
didn't implement #respond_to? correctly, but that could be fixed!

So I think #respond_to? is the right method to be querying. Does this make
sense? If not, can you put your finger on what exactly it is you don't like?
Here are some fuller examples that may make things clearer...

class Sheep
  def chew(food); end
  def self.number_of_legs; 4 end
end

sheep = mock()
sheep.responds_like(Sheep.new)
assert sheep.respond_to?(:chew)
sheep.expects(:chew).with('grass')
sheep.chew('grass')

sheep_class = mock
sheep_class.responds_like(Sheep)
assert sheep_class.respond_to?(Sheep)
sheep_class.stubs(:number_of_legs).returns(2)
assert_equal 2, sheep_class.number_of_legs

If constructing a Sheep instance in the test is undesirable, use the
#instance_of method...

sheep = mock()
sheep.responds_like(instance_of(Sheep))
assert sheep.respond_to?(:chew)
sheep.expects(:chew).with('grass')
sheep.chew('grass')

This last example is the one I'm least happy with, especially as it may well
be the most common scenario.

Any more ideas?

Thanks.
-- 
James.
http://blog.floehopper.org


More information about the mocha-developer mailing list