[rspec-users] stub_model() and ActiveRecord Associations

Matt Wynne matt at mattwynne.net
Tue Aug 26 14:34:17 EDT 2008

Hi all,

I have what I thought was quite a simple requirement but something to  
do with the way ActiveRecord's associations work is making it quite  

I guess I can sum it up with this failing test:

         before(:each) do
           @source_comment = @source.comments.create(:user_id => 1)
           @target_comment = @target.comments.create(:user_id => 1)

         it "should return the same object from create() as from the  
array" do

           (@target_comment.equal?(@target.comments[0])).should be_true



What I actually want to be able to do, is mock a method call on the  
@target_comment but I'm finding that I get unreliable results:

           @target.comments[0].should_receive(:merge_in) # works
#          @target_comment.should_receive(:merge_in) # doesn't work

The code I'm testing is using self.comments.each() to access the  
object it's going to call merge_in() on - the one I want to mock.

Any tips here folks?

Someone here has suggested that what I really need to do is express  
my mock like... (commence pseudo code)

(...).on_an_object_matching{|o| o.id = @target_comment.id}

(/pseudo code)

Has anyone else come across similar issues? How did you approach them?


In case you wondered: The opinions expressed in this email are my own  
and do not necessarily reflect the views of any former, current or  
future employers of mine.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/rspec-users/attachments/20080826/ee5a542d/attachment.html>

More information about the rspec-users mailing list