Using factory_girl with declarative_authorization

I recently added declarative_authorization to a Rails app that uses FactoryGirl with RSpec. As Mark Needham pointed out around two years ago at, this can cause problems because FactoryGirl can’t save records without the appropriate authorization. Mark’s suggestion was to use monkey patching to wrap around the create method, but I had some issues attempting to implement this. I suspect the internals of FactoryGirl have changed since Mark posted.

After extensive poking around and trial and error, I stumbled across, which has a whole discussion about callback support that was added in FactoryGirl 3.3.0 (which was less than six months old at the time of this posting). It first occurred to me to use the before(:create) and after(:create) to set Authorization.current_user, but after I read to the end of the post I realized that to_create was exactly what I needed.

All I had to do was to create the file spec/factories.rb and added the following code to it:

require 'declarative_authorization/maintenance'
include Authorization::TestHelper

FactoryGirl.define do
  to_create do |instance|
    without_access_control {! }

Voila! No monkey patching, and I only have to create one file and all my calls to FactoryGirl.create start working again.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s