[rspec-users] Problems with mock assigned to a constant

Matt Lins mattlins at gmail.com
Fri Jul 25 01:05:30 EDT 2008

On Thu, Jul 24, 2008 at 11:38 PM, Scott Taylor
<mailing_lists at railsnewbie.com> wrote:
> On Jul 25, 2008, at 12:21 AM, Matt Lins wrote:
>> Scott,
>> Thanks, your solution does work, although I'm not sure I like it.  I
>> like to stub out behavior in my before block but also use mock
>> expectations to verify behavior in my specs.  Similar to what Dave
>> explains here:
>> http://blog.davidchelimsky.net/2006/11/9/tutorial-rspec-stubs-and-mocks
>> I defined the stubs in the before block:
>> MyModel = mock('MyModel Class', :count => 1, :find => [@record])
> Ah - well, I missed this part.  This make much more sense.
> Btw, aren't you seeing warnings every time you run your specs?

I'm not sure what code you're looking at, but in the gist paste I
posted for this thread, I'm only defining the constant once(
before(:all) ).  If you're looking at the lighthouse code, I was
undefining the constants in the after block.  So, no, I'm not seeing

> Redefining the constant for your test, is, IMHO, the most ugly solution you
> can take (and plus, it'll break in many circumstances - for instance, it
> probably wont' play well with rails loading schemes).  One way around this
> is by using dependency injection - I would highly recommend you use this
> technique.  *DON'T* use the constant technique, unless you really know what
> your doing.

Like I said I'm not redefining the constants.  Thanks for the insight,
I'll research DI.

> Unfortunately there are times when DI doesn't work (especially in the rails
> world) - in those cases, you really have no other option besides stubbing
> the class methods directly.
>> wiping out the stubs defined in the before block?  If that is the case
>> why does the first spec not fail because of MyModel.find ?
> Well - what is happening between each test case?  Are the classes (defined
> elsewhere) being reloaded each time?  Are you getting a warning when you
> redefine MyModel?  Do you understand how rails is (re)loading this stuff?

All my code for the example was posted in gist ( you can download it
if you'd like ).  I'm not using Rails, I'm writing a library that uses
ActiveRecord.  But, all that is mocked out.  The example in gist fully
illustrates the problem in my actual library.  The output that I
posted in the first post is exactly what you get if you run the code
pasted in gist:


Sorry, if that was confusing, I shouldn't have even mentioned the
lighthouse ticket.

> Scott
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users

More information about the rspec-users mailing list