I've added a method to the mock class that makes it pretty easy to
stub associations in rails. I've been using it for awhile and it seems
to cut down on a lot of setup code for the controller and model specs
that use associations.
#before
@person = mock_model(Person)
posts = mock('post_proxy')
posts.stub!(:build).and_return(mock_model(Post, :save => true))
@person.stub!(:posts).and_return(posts)
# now
@person = mock_model(Person)
@person.stub_association!(:posts, :find_by_title => mock_model(Post))
Just add this to the spec helper
module Spec
module Mocks
module Methods
def stub_association!(association_name, methods_to_be_stubbed = {})
mock_association = Spec::Mocks::Mock.new(association_name.to_s)
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)
end
end
end
end