[rspec-users] Problems with mock assigned to a constant
mailing_lists at railsnewbie.com
Fri Jul 25 01:16:28 EDT 2008
On Jul 25, 2008, at 1:05 AM, Matt Lins wrote:
> 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:
>>> 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:
>>> 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
>> 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
>> the class methods directly.
>>> wiping out the stubs defined in the before block? If that is the
>>> why does the first spec not fail because of MyModel.find ?
>> Well - what is happening between each test case? Are the classes
>> elsewhere) being reloaded each time? Are you getting a warning
>> when you
>> redefine MyModel? Do you understand how rails is (re)loading this
> 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.
No - it was my own fault. I didn't take the time to read your post
Anyway - DI is surely the way to go. And generally you'll want to
stay away from before(:all) when you can.
More information about the rspec-users