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

Scott Taylor mailing_lists at railsnewbie.com
Fri Jul 25 00:47:13 EDT 2008

On Jul 25, 2008, at 12:32 AM, Matt Lins wrote:

> I suppose the way I'm defining the stubs, differs from what Dave is
> doing in his example.
> I assumed that:
> MyModel = mock('MyModel Class', :count => 1)
> was the same as:
> MyModel.stub!(:count).and_return(1)

Nope.  Not even close.  Here's an equivalent of the first form:

Object.send :remove_const, :MyModel
MyModel = <a mock object>

and here's the second form:

MyModel.instance_eval do
   def count


MyModel.class_eval do
   class << self
     def count; 1; end


> But, I'm starting to think they are not.  I haven't looked at the
> rSpec internals to verify, other than the parameter name:
> stubs_and_options+ lets you assign options and stub values
> at the same time. The only option available is :null_object.
> Anything else is treated as a stub value.
> So, is this problem?

Yeah - so here are two related, but not equivalent ideas: mock  
objects, and stubs.  A stub is just a faked out method - it can exist  
on a mock object (a completely fake object), or on a partial mock  
(i.e. a real object, with a method faked out).  mock('My mock") is a  
mock object, MyRealObject.stub!(:foo) is a real object with the method  
foo faked out.

What is the difference between a mock object and a fake object?  A  
mock object will complain (read: raise an error) any time it receives  
a message which it doesn't understand (i.e. one which hasn't been  
explicitly stubbed).  A real object will work as usual.  (A null  
object mock is a special type of mock - one which never complains.   
For now, you shouldn't worry about it).

Hope this helps,


More information about the rspec-users mailing list