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): Easy AR association stubbing - RSpec - Ruby-Forum
Are those two methods currently the accepted “best practice” for
mocking and stubbing calls such like these?:
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): Easy AR association stubbing - RSpec - Ruby-Forum
Are those two methods currently the accepted “best practice” for
mocking and stubbing calls such like these?:
I don’t know about any “best practice”. In the realm of TDD vs
ActiveRecord Associations, you’re looking at something more like
“least-worst” practice, IMO. The way the AssociationCollections behave
is pretty complex and difficult to simulate with a simple mock or two.
I started out trying to stay ‘pure’ and not touch the database, but
TBH, these days I’ve given up the fight and mostly just throw a few
records in a database table - that way you can actually specify the
behaviour you want rather than the gory implementation details.
As you can probably tell by my grumbling, this is one of my least
favourite bits of working on rails.
Saying that, it is often still reasonable, I think, to fake an
association proxy collection using an array that’s patched with a few
extra methods. We have a helper method in the Songkick spec code
that’s called something like FakeCollection, which subclasses array
and has a few helpful methods to make it look enough like an
association collection to make the specs run OK.
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:
Thanks for pointing out that article, Baz. Luke’s suggestions are an
interesting method of dealing with this. I’m going to give it a try
when I have some time.
-Nick
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
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