[rspec-users] Mocking and stubbing model relationships

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


On 2008-11-19, at 12:26, Chris Flipse wrote:
> I've actually taken this old gem and enhanced it a bit
>
> module Spec::Mocks::Methods
>   def stub_association!(association_name, methods_to_be_stubbed ={})
>     mock_assn = Spec::Mocks::Mock.new(association_name.to_s)
>     stub_association_with(association_name, mock_assn,  
> methods_to_be_stubbed)
>   end
>
>   def stub_association_with(association_name, values,  
> methods_to_be_stubbed = {})
>     methods_to_be_stubbed.each do |meth, return_value|
>         values.stub!(meth).and_return(return_value)
>     end
>     yield(values) if block_given?
>
>     self.stub!(association_name).and_return(values)
>   end
> end
>
> This lets me specify the "contents" of an association:
>
> foo.stub_association_with(:bar, [@bar1, @bar2, @bar3], :find => @bar1)
>
> and also gives me some more fine grained control about stubbing the  
> association
>
> foo.stub_association_with(:bar, [@bar1, @bar2, @bar3]) do |assn|
>   assn.stub!(:find).with(1).and_return @bar1
>   assn.stub!(:find).with(2).and_return @bar2
>   assn.stub!(:find).with(5).and_raise RecordNotFound
> end

Sending in a block like that is a great idea.


More information about the rspec-users mailing list