File tree Expand file tree Collapse file tree 3 files changed +29
-0
lines changed
Expand file tree Collapse file tree 3 files changed +29
-0
lines changed Original file line number Diff line number Diff line change @@ -49,6 +49,8 @@ class ActiveModelErrorSerializer < ErrorSerializer
4949 { pointer : "/data/attributes/#{ error_key } " }
5050 elsif rels . include? ( error_key )
5151 { pointer : "/data/relationships/#{ error_key } " }
52+ elsif error_key == :base
53+ { pointer : "/data" }
5254 else
5355 { pointer : '' }
5456 end
Original file line number Diff line number Diff line change @@ -43,6 +43,7 @@ def self.ransackable_associations(auth_object = nil)
4343class Note < ActiveRecord ::Base
4444 validates_format_of :title , without : /BAD_TITLE/
4545 validates_numericality_of :quantity , less_than : 100 , if : :quantity?
46+ validate :title_check
4647 belongs_to :user , required : true
4748
4849 def self . ransackable_associations ( auth_object = nil )
@@ -52,6 +53,11 @@ def self.ransackable_associations(auth_object = nil)
5253 def self . ransackable_attributes ( auth_object = nil )
5354 %w( created_at id quantity title updated_at user_id )
5455 end
56+
57+ # Provide a validation adding an error to the model's base
58+ def title_check
59+ errors . add ( :base , :invalid ) if title == 'n/a'
60+ end
5561end
5662
5763class CustomNoteSerializer
Original file line number Diff line number Diff line change 138138 . to eq ( 'pointer' => '/data/attributes/title' )
139139 end
140140 end
141+
142+ context 'with a validation error on the class' do
143+ let ( :params ) do
144+ payload = note_params . dup
145+ payload [ :data ] [ :attributes ] [ :title ] = 'n/a'
146+ payload
147+ end
148+
149+ it do
150+ expect ( response ) . to have_http_status ( :unprocessable_entity )
151+ expect ( response_json [ 'errors' ] . size ) . to eq ( 1 )
152+ expect ( response_json [ 'errors' ] [ 0 ] [ 'status' ] ) . to eq ( '422' )
153+ expect ( response_json [ 'errors' ] [ 0 ] [ 'code' ] ) . to include ( 'invalid' )
154+ expect ( response_json [ 'errors' ] [ 0 ] [ 'title' ] )
155+ . to eq ( Rack ::Utils ::HTTP_STATUS_CODES [ 422 ] )
156+ expect ( response_json [ 'errors' ] [ 0 ] [ 'source' ] )
157+ . to eq ( 'pointer' => '/data' )
158+ expect ( response_json [ 'errors' ] [ 0 ] [ 'detail' ] )
159+ . to eq ( 'is invalid' )
160+ end
161+ end
141162 end
142163
143164 context 'with a bad note ID' do
You can’t perform that action at this time.
0 commit comments