The Pug Automatic

Bypassing attr_accessible/attr_protected for test factories

Written October 4, 2007. Tagged Ruby, Ruby on Rails.

Using attr_accessible/attr_protected to secure your models during mass-assignment is a good idea – when you're mass-assigning unsafe user-provided data.

If you use factory methods for tests, though, or do trusted mass-assignment elsewhere, you might want a way to bypass the protection.

I added this to test/test_helper.rb:

class ActiveRecord::Base
def self.unprotected_create!(*args)
previous_attr_protected = read_inheritable_attribute("attr_protected")
previous_attr_accessible = read_inheritable_attribute("attr_accessible")

write_inheritable_attribute("attr_protected", nil)
write_inheritable_attribute("attr_accessible", nil)

creation = create!(*args)

write_inheritable_attribute("attr_protected", previous_attr_protected)
write_inheritable_attribute("attr_accessible", previous_attr_accessible)


Then just use unprotected_create! instead of create! for your factories.