[rspec-users] stub_model() and ActiveRecord Associations

Matt Wynne matt at mattwynne.net
Wed Aug 27 08:38:43 EDT 2008


On 27 Aug 2008, at 13:26, David Chelimsky wrote:

> On Wed, Aug 27, 2008 at 7:22 AM, Zach Dennis  
> <zach.dennis at gmail.com> wrote:
>> On Wed, Aug 27, 2008 at 3:34 AM, Matt Wynne <matt at mattwynne.net>  
>> wrote:
>>>> Here's the basic deal:
>>>>
>>>> Model.find(1).equal?(Model.find(1))
>>>> => false
>>>>
>>>> AR does not cache objects, so when you ask it for what you *think*
>>>> might the same object twice, you get different ones.
>>>
>>> I thought as much... So does AR just cache the object's  
>>> attributes instead
>>> and construct them on the fly as and when you ask for them?
>>
>>
>> It caches the SQL statements and their results. It uses the cached
>> results to build an instance of your model. Although the identify of
>> the objects are different, they are equal.
>>
>>    f = Foo.create :name => "blah"
>>    f.equal?(Foo.last) # false
>>    f == Foo.last       # true
>>
>> I don't know your ultimate goal,
>
> He's trying to set a message expectation on an object that gets
> returned by AR. Since AR builds a new object for each request, you
> can't get a handle on it in the code example.

You've got it. I worked around it using the foo.stub!(:bars) = []  
hack, but I too feel dirty about it.

I think I'm going to need a couple of old-fashioned database-coupled  
tests to prove to myself that all this works OK.


More information about the rspec-users mailing list