[rspec-users] Mocking and stubbing Rails' has_many association

Eirik Dentz Sinclair eirik at imap.cc
Tue Apr 15 13:10:13 EDT 2008

I'm somewhat new to testing and rspec. And I'm struggling a bit with  
the application of Mocks and Stubs in a Rails application. I think I'm  
beginning to grasp it, but I'm stuck on how to spec the following:

I have a User model which has a has_many relationship to Trip models,  
and the implementation is taken from http://railscasts.com/episodes/75  
So I have the following methods in my User model to handle the nested  
Trip attributes that are passed to the User model:

def new_trip_attributes=(trip_attributes)
   trip_attributes.each do |attributes|

def existing_trip_attributes=(trip_attributes)
   trips.reject(&:new_record?).each do |trip|
     attributes = trip_attributes[trip.id.to_s]
     if attributes
       trip.attributes = attributes

Part of my problem is probably that I'm not doing true T/B driven  
development, but trying to spec Ryan's implmentation. Anyway for the  
new_trip_attributes= method I've come up with the following spec:

it "should use new trip attributes to add Trips to the trips  
association" do
   @user.stub_association!(:trips, :build => mock_model(Trip, :save =>  
   @user.new_trip_attributes = trip_attributes

(I found the stub_association! method here: http://www.ruby-forum.com/topic/126993) 
  This seems to work, though I'm not sure that the single example is  
sufficient coverage for that method...

But where I'm really running into trouble is with the  
existing_trip_attributes= method. I've been trying to puzzle through  
it using this thread as a guideline: http://www.ruby-forum.com/topic/138342

These are the examples I came up with to cover the method

it "should ignore new associated trip records"

it "should update the associated existing trip"

it "should delete the associated existing trip, if there are no  
attributes for it"

I'm really not sure what to mock, what to stub or even if my confusion  
is an indication that the method implementation should be different.  
Beyond my specific implementation question, It would be great to hear  
from more experienced Rspec users on how to discern the difference  
between ones capability with the tool (Rspec), vs. the tool's feedback  
that the implementation needs to be changed.

I have studied the first three peepcode rspec episodes as well as the  
altered beast specs http://git.caboo.se/?p=altered_beast.git;a=summary  
and done a bit of searching and reading through the list archives. The  
Altered beast specs are enlightening, but they make use of some  
extensions to Rspec and I would rather not confuse myself with trying  
to learn those extensions at the same time. Any other suggestions for  
open source rails projects with good specs to learn from would be  
appreciated as well.

Thanks in advance for any suggestions you might have.

Eirik Dentz Sinclair

More information about the rspec-users mailing list