[rspec-users] Mocking and stubbing model relationships

Nick Hoffman nick at deadorange.com
Thu Nov 20 12:43:03 EST 2008


On 2008-11-18, at 15:49, Ben Mabey wrote:
> Nick Hoffman wrote:
>> Before writing specs for a one-to-many relationship between two  
>> models, I did some research and found that some people were  
>> creating proxy mocks, and others were using Matthew Heidemann's  
>> #stub_association! (which essentially does that for, but in a nice,  
>> DRY way):
>>  http://www.ruby-forum.com/topic/126993
>>
>> Are those two methods currently the accepted "best practice" for  
>> mocking and stubbing calls such like these?:
>>
>> @properties = @user.properties
>> @property = @user.properties.new
>> @property = @user.properties.find_by_id params[:id]
>>
>> Thanks,
>> Nick
>
> I like to place this in my spec_helper.rb:
>
> module Spec
> module Mocks
>   module Methods
>     def stub_association!(association_name, methods_to_be_stubbed =  
> {})
>       mock_association = Spec::Mocks::Mock.new("#{association_name}  
> association")
>       methods_to_be_stubbed.each do |method, return_value|
>         mock_association.stub!(method).and_return(return_value)
>       end
>       self.stub!(association_name).and_return(mock_association)
>       mock_association
>     end
>   end
> end
> end
>
>
>
> The you can say stuff like:
>
> @user.stub_association!(:properties, :new =>  
> mock_model(Property), :find_by_id => mock_model(Property))
>
> HTH,
> Ben

That's very similar to Matthew Heidemann's #stub_association! . I  
can't say who wrote it first, though  =)  Regardless, that's what I've  
been using, and find it to be quite efficient.
-Nick


More information about the rspec-users mailing list