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

Pat Maddox pergesu at gmail.com
Fri Jul 25 12:28:20 EDT 2008

On Fri, Jul 25, 2008 at 9:30 AM, Matt Lins <mattlins at gmail.com> wrote:
> Yes, gist is great!
> Thank you very much for taking the time to look at this.  I like your
> suggestions very much and will use them.  At this point I'm just
> messing around, but I don't understand why this doesn't work.
> One more bad implementation if you have time:
> http://gist.github.com/2372
> I'm removing the constant after each spec runs and redefining it
> before each runs.  The second spec still doesn't pass though, even
> though the constant is defined before each spec.
> Again, I realize this is horrible, but it should still work, no?

I think you're right, there is something funky going on, and I *think*
it's something internal to RSpec.  Your code looks like it ought to
work, and it works in Mocha.  I've poked around a little bit, but
nothing jumped out at me.

That said, this is a pretty weird edge case and afaik has not affected
anything I've ever done.  I can tell you that this is an uber-low
priority, for me at least, so you'll either have to hope it piques
someone's curiosity enough to fix, or go ahead and work on a fix

As you've pointed out, you can do
class MyModel; end
MyModel.stub!(:count).and_return 1
MyModel.stub!(:find).and_return [@record]

I've just committed a small enhancement that lets you do
MyModel.stub!(:count => 1, :find => [@record])

in order to cut down on the noise.

Download the latest source and build your gem and you're good to go.

Also, you can do as Scott suggested and use DI.  Then you'd be doing
something like
Migration.set_model MyModel

I agree though that this may not be desirable in some cases.  For
instance, if the constant name is represented as a string (such as in
a DB column) then you've now put the burden on client code to do the
string->constant conversion.


More information about the rspec-users mailing list