April 24, 2009
Feature Request: Stub chaining in RSpec
ActiveRecord associations often require testing long chains of method calls, using mock objects as such:
1 @comments_association = mock(:comments
2 Blog.stub!(:comments).andreturn(@commentsassociation)
3 @comments = [ mock_model(Comment) ]
4 @commentsassociation.stub!(:recent).andreturn(@comments)
5
6 Blog.comments.recent
7
It would improve readability if we could specify a chain of stubs more succinctly: 1 @comments = [ mock_model(Comment) ]
2 Blog.mock!(:comments, :recent => @comments)
3
Essentially, the mock! method above is both creating a mock object and returning it from the stub defined at Blog.comments.
Presumably, we could also pass in arguments:
1 Blog.mock!(:comments, :recent => @comments).with(:limit => 5)
2
I've filed this as a feature request with the RSpec team. Do you have any elegant solutions for stubbing chains of objects?