[mocha-developer] Parameter Matchers with optional params

Andrew Vit andrew at avit.ca
Tue Sep 25 13:53:32 EDT 2007

Sounds great... I'm all for syntactic sugar.

I'm pretty new to TDD and especially to mocking, so I'm sure I'm  
overreaching a bit for what I'm trying to do.

Do you guys ever use any helper methods to set up pre-fab mock  
objects for your test cases? Because that's what I'm trying to do for  
my ActiveRecord models, and it was tripping up depending an the exact  
parameters of the find method, hence my original question:

module Factory

   def self.method_missing( name, *args )
     # returns either a plain ActiveRecord Model.new with sensible,  
     # model attributes, (not shown for clarity) or runs it through
     # self.proxy to make a mock if the method name has /^proxy_/

   # give me a model that's "saved" to satisfy associations:

   def self.proxy( obj, obj_id )
     obj.stubs(:id).returns obj_id
     obj.stubs(:valid?).returns true
     obj.stubs(:new_record?).returns false
     obj.class.stubs(:find).with(){ |*args| args[0].class ==  
Fixnum }.returns obj


I found I was using the above pattern a lot, to stub out saved AR  
objects to satisfy model associations, so I tried to abstract it into  
this helper. However, I sometimes call the find directly with just  
find(id), and the rest of the time it's called by ActiveRecord to  
validate the association, and that's why I needed to match & ignore  
any extra params.


On Sep 25, 2007, at 1:40 AM, James Mead wrote:

> Andrew - Sorry. I also meant to say that I am confident that any  
> replacement
> for this style of matching will be versatile enough. I have two or  
> three
> ideas knocking around at the moment.

More information about the mocha-developer mailing list