[mocha-developer] Stubbing ActiveRecord Models gets very difficult with instance methods

jpywtora at calpoly.edu jpywtora at calpoly.edu
Tue Dec 19 03:39:55 EST 2006

I have seen some basic examples of using Mocha and Stubba with ActiveRecord Models;  However, the ones I read were somewhat simplistic.  That is they stubbed the find class method of the model, or the execute method of the connection object.  While stubbing the find method had the desired effect for the author it did not help with a situation I was hacking away on.  Which was writing a test case for an instance method of a model.  I wanted to eliminate the database connection and select_all calls with stubs in my test methods.  Thus, my class finders would return real AR objects.

Stubbing the find method obviously makes the class method return objects that are close enough; However, to test instance methods for your model you need real ActiveRecord objects.  You can make stubs for all the attributes, but the instance methods under test need to be there.  This is the problem I could not overcome, at least in today's hacking attempts.  Another ActiveRecord hickup is the trip the it makes to the database to discover the Model attributes, so do you allow that to still occur?  Do it in the setup of your test case?

I suppose one could put these important methods in a module and mix them in to the model, but this seems slightly off as a comprise for testing sake.  Any thoughts anyone?  Maybe this is not the right place for Mocha and Stubba?  Maybe this is just the type of thing a real test database and test cases are the best solution.  Something like the Rails fixture approach.

I was able to solve my specific case by making my instance method a class method, which turned out to be a better fit; However, it left me wondering and that is why I ask.


More information about the mocha-developer mailing list