blob: 490b599fb67a8bdb4347f9407837bcc2c8e5326d (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
require 'cases/helper'
require 'active_support/core_ext/hash/indifferent_access'
require 'models/person'
require 'models/company'
class ProtectedParams < ActiveSupport::HashWithIndifferentAccess
attr_accessor :permitted
alias :permitted? :permitted
def initialize(attributes)
super(attributes)
@permitted = false
end
def permit!
@permitted = true
self
end
def dup
super.tap do |duplicate|
duplicate.instance_variable_set :@permitted, @permitted
end
end
end
class ForbiddenAttributesProtectionTest < ActiveRecord::TestCase
def test_forbidden_attributes_cannot_be_used_for_mass_assignment
params = ProtectedParams.new(first_name: 'Guille', gender: 'm')
assert_raises(ActiveModel::ForbiddenAttributesError) do
Person.new(params)
end
end
def test_permitted_attributes_can_be_used_for_mass_assignment
params = ProtectedParams.new(first_name: 'Guille', gender: 'm')
params.permit!
person = Person.new(params)
assert_equal 'Guille', person.first_name
assert_equal 'm', person.gender
end
def test_forbidden_attributes_cannot_be_used_for_sti_inheritance_column
params = ProtectedParams.new(type: 'Client')
assert_raises(ActiveModel::ForbiddenAttributesError) do
Company.new(params)
end
end
def test_permitted_attributes_can_be_used_for_sti_inheritance_column
params = ProtectedParams.new(type: 'Client')
params.permit!
person = Company.new(params)
assert_equal person.class, Client
end
def test_regular_hash_should_still_be_used_for_mass_assignment
person = Person.new(first_name: 'Guille', gender: 'm')
assert_equal 'Guille', person.first_name
assert_equal 'm', person.gender
end
end
|