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, [EMAIL PROTECTED], @bar2, @bar3], :find => 
@bar1)

and also gives me some more fine grained control about stubbing the
association

foo.stub_association_with(:bar, [EMAIL PROTECTED], @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



On Tue, Nov 18, 2008 at 3:49 PM, Ben Mabey <[EMAIL PROTECTED]> wrote:

> 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
>
>
> _______________________________________________
> rspec-users mailing list
> rspec-users@rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>



-- 
// anything worth taking seriously is worth making fun of
// http://blog.devcaffeine.com/
_______________________________________________
rspec-users mailing list
rspec-users@rubyforge.org
http://rubyforge.org/mailman/listinfo/rspec-users

Reply via email to