Nick Hoffman wrote:
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
_______________________________________________
rspec-users mailing list
rspec-users@rubyforge.org
http://rubyforge.org/mailman/listinfo/rspec-users
Probably Matt.. I can't remember who posted it first... But I got it from the list a while ago and it has been very useful in a lot of my apps.
-Ben
_______________________________________________
rspec-users mailing list
rspec-users@rubyforge.org
http://rubyforge.org/mailman/listinfo/rspec-users

Reply via email to