ActiveRecord PassportControl plugin

One of the things that irritates me from time to time about testing Rails code is when you can't easily mock the object you want. It usually comes up in a controller test where you create an AR instance in your setup but, because you pass it by id into the controller, the controller retrieves a difference instance of the record.

You can solve this by mocking the AR model class but this can get messy. What I really wanted was a way to mock a record rather than an instance so I whipped up the Passport Control plugin. This lets me write:

setup do
  @user = User.make
  @content = @user.contents.make
  @content.at_passport_control { |content| mock( content ).foo { "foo!" }
  get :show, :id => @content.id
end

The call to at_passport_control ensures that whenever this record (as identified by it's id) is instantiated by ActiveRecord, by whatever chain of invocations, that it will have it's #foo method mocked.

Comes with a Test::Unit adapater and seems to work well for me. Hope you find Passport Control useful too.

18/06/2009 08:55 by Matt Mower | Permalink | comments: