diff --git a/lib/bright_serializer/serializer.rb b/lib/bright_serializer/serializer.rb index 6801839..168a71c 100644 --- a/lib/bright_serializer/serializer.rb +++ b/lib/bright_serializer/serializer.rb @@ -22,7 +22,7 @@ def self.included(base) def initialize(object, **options) @object = object - @params = options.delete(:params) + @params = options.delete(:params) || {} @fields = options.delete(:fields) end diff --git a/spec/bright_serializer/serializer_params_spec.rb b/spec/bright_serializer/serializer_params_spec.rb index f17b971..a3f13a3 100644 --- a/spec/bright_serializer/serializer_params_spec.rb +++ b/spec/bright_serializer/serializer_params_spec.rb @@ -15,7 +15,7 @@ "#{object.first_name} #{object.last_name}" end attribute :params do |object, params| - "#{object.first_name} #{object.last_name} #{params}" + "#{object.first_name} #{object.last_name} #{params[:suffix]}".strip end attribute :params_upcase do |object, params| @@ -23,12 +23,12 @@ end def upcase(object, params) - "#{object.first_name} #{object.last_name} #{params}".upcase + "#{object.first_name} #{object.last_name} #{params[:suffix]}".upcase.strip end end end - let(:instance) { serializer_class.new(user, params: param) } + let(:instance) { serializer_class.new(user, params: { suffix: param }) } let(:param) { Faker::Lorem.word } let(:result) do @@ -44,5 +44,20 @@ def upcase(object, params) it 'serialize params' do expect(instance.to_hash).to eq(result) end + + context 'when not passing params' do + # The anonymous serializer assumes params is always a hash and calls params[:suffix] directly. + # This test ensures that when params is not passed, it is treated as an empty hash without raising an error. + it 'passes an empty hash' do + instance = serializer_class.new(user) + expect(instance.to_hash).to eq( + first_name: user.first_name, + last_name: user.last_name, + name: "#{user.first_name} #{user.last_name}", + params: "#{user.first_name} #{user.last_name}", + params_upcase: "#{user.first_name} #{user.last_name}".upcase + ) + end + end end end