Bypassing attr_accessible/attr_protected for test factories

Written . 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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)

    creation
  end
end

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