From f7b3813fbe60b6dcf288f6ac3e7586badeb7e717 Mon Sep 17 00:00:00 2001 From: Matt-Yorkley <9029026+Matt-Yorkley@users.noreply.github.com> Date: Tue, 30 Mar 2021 14:45:33 +0100 Subject: [PATCH] Defend against nils in variant serializer If unit_price.denominator ever returns nil, the serializer won't explode now. --- app/serializers/api/variant_serializer.rb | 2 +- .../serializers/api/variant_serializer_spec.rb | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/app/serializers/api/variant_serializer.rb b/app/serializers/api/variant_serializer.rb index ecbfc66dc7b..06d841c3924 100644 --- a/app/serializers/api/variant_serializer.rb +++ b/app/serializers/api/variant_serializer.rb @@ -41,7 +41,7 @@ def thumb_url end def unit_price_price - price_with_fees / unit_price.denominator + price_with_fees / (unit_price.denominator || 1) end def unit_price_unit diff --git a/spec/serializers/api/variant_serializer_spec.rb b/spec/serializers/api/variant_serializer_spec.rb index 730f91127d7..26550a8f0b7 100644 --- a/spec/serializers/api/variant_serializer_spec.rb +++ b/spec/serializers/api/variant_serializer_spec.rb @@ -25,4 +25,22 @@ :tag_list # Used to apply tag rules ) end + + describe "#unit_price_price" do + context "without fees" do + it "displays the price divided by the unit price denominator" do + allow(subject).to receive_message_chain(:unit_price, :denominator) { 1000 } + + expect(subject.unit_price_price).to eq(variant.price / 1000) + end + end + + context "when the denominator returns nil" do + it "returns the price" do + allow(subject).to receive_message_chain(:unit_price, :denominator) { nil } + + expect(subject.unit_price_price).to eq(variant.price) + end + end + end end