Problems with mock assigned to a constant

On Fri, Jul 25, 2008 at 9:30 AM, Matt L. [email protected] wrote:

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
yourself.

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.

Pat

Yah, I looked around. I came out with a better understanding of
rSpec’s mocking internals, but no answer to the problem.
I don’t need it. I’ll probably end up using FlexMock or Mocha for
future projects anyway. I’d be happy to file a ticket if you think
it’s worthy of one. It was my first implementation of the spec and I
thought it should work. I’ve since refactored with Dave’s
suggestions.

I’m not so sure about DI in this scenario. I couldn’t find any decent
examples of it’s use in rSpec and I’m happy with what I have now.

Thanks again everyone.