Skip to main content

Rails Gotcha: Mocking/Stubbing on an Associated ActiveRecord Object

Blog post   •   Feb 24, 2010 16:34 GMT

In RSpec it is still not possible to have mocks or stubs on all instances of a class, although this has been suggested and it is a feature of the Mocha framework. Stubbing or mocking an object returned by an ActiveRecord belongs_to association (i.e. article.author) won't do what you expect. Instead of mocking the associated object you end up mocking the AssociationProxy object that wraps the associated object. To work around this you can use the AssociationProxy#proxy_target method, something like this:

gist

So when we think we are working directly with an ActiveRecord model, we are in fact working with a proxy object, and this can be confusing:

gist

As far as I can tell this behaviour won't change with Rails 3 since its AssociationProxy class works the same way.

Comments (2)

    Pardon min swedish ;)

    Bra tips! En annan bra grej är att stubba ut Autotest#rerun_all_tests när suiten av tester blir större, helt omöjligt att använda autospec annars.

    - Jon - Feb 24, 2010 23:17 GMT

    Hi!

    Thanks for such a knowledgeable post.

    <a href="http://airul.id/tech/">Airultech</a>

    - Market Research Vietnam - May 13, 2016 08:39 GMT

Add comment

Comment