I recently added declarative_authorization
to a Rails app that uses FactoryGirl with RSpec. As Mark Needham pointed out around two years ago at http://www.markhneedham.com/blog/2010/09/12/ruby-factorygirl-declarative_authorization-random-thoughts/, 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 http://robots.thoughtbot.com/post/23039827914/get-your-callbacks-on-with-factory-girl-3-3, 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 { instance.save! } end end
Voila! No monkey patching, and I only have to create one file and all my calls to FactoryGirl.create
start working again.