File tree Expand file tree Collapse file tree 2 files changed +45
-0
lines changed Expand file tree Collapse file tree 2 files changed +45
-0
lines changed Original file line number Diff line number Diff line change @@ -24,6 +24,18 @@ def full_messages
24
24
map { |attribute , message | full_message ( attribute , message ) }
25
25
end
26
26
27
+ # Allow ActiveSupport to render errors similar to ActiveModel::Errors
28
+ def as_json ( options = nil )
29
+ Hash . new . tap do |output |
30
+ raise NotImplementedError . new unless output . respond_to? ( :as_json )
31
+
32
+ self . each do |field , value |
33
+ output [ field ] ||= [ ]
34
+ output [ field ] << value
35
+ end
36
+ end . as_json ( options )
37
+ end
38
+
27
39
private
28
40
def full_message ( attribute , message )
29
41
return message if attribute == :base
Original file line number Diff line number Diff line change 80
80
end
81
81
end
82
82
83
+ describe "#as_json" do
84
+ it "raises a NotImplementedError" do
85
+ expect { errors . as_json } . to raise_error SimpleCommand ::NotImplementedError
86
+ end
87
+
88
+ context "when Hash supports as_json" do
89
+ module HashAsJsonMixin
90
+ # Mock example of as_json from ActiveSupport
91
+ def as_json ( options )
92
+ JSON . parse ( to_json ( options ) )
93
+ end
94
+ end
95
+
96
+ around do |example |
97
+ inject_required = !Hash . new . respond_to? ( :as_json )
98
+ Hash . include HashAsJsonMixin if inject_required
99
+ example . run
100
+ Hash . undef_method ( :as_json ) if inject_required
101
+ end
102
+
103
+ it "groups errors by key values" do
104
+ errors . add :attr1 , 'has an error'
105
+ errors . add :attr2 , 'has an error'
106
+ errors . add :attr2 , 'has two errors'
107
+
108
+ expect ( errors . as_json ) . to eq (
109
+ "attr1" => [ "has an error" ] ,
110
+ "attr2" => [ "has an error" , "has two errors" ]
111
+ )
112
+ end
113
+ end
114
+ end
115
+
83
116
describe "#to_json" do
84
117
it "groups errors by key values" do
85
118
errors . add :attr1 , 'has an error'
You can’t perform that action at this time.
0 commit comments