From e29e0c049e6899f153a24ba9e191447d8011645b Mon Sep 17 00:00:00 2001 From: Washington Botelho Date: Thu, 8 Feb 2018 18:37:13 -0200 Subject: [PATCH] fix: avoid error when has no rate record --- lib/rating/models/rating/rating.rb | 2 +- spec/models/rating/update_rating_spec.rb | 22 ++++++++++++++++++++-- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/lib/rating/models/rating/rating.rb b/lib/rating/models/rating/rating.rb index 1a441f9..a5c4dfa 100644 --- a/lib/rating/models/rating/rating.rb +++ b/lib/rating/models/rating/rating.rb @@ -101,7 +101,7 @@ module Rating count = distinct ? 'COUNT(DISTINCT resource_id)' : 'COUNT(1)' %(( - SELECT #{count} + SELECT GREATEST(#{count}, 1) FROM #{rate_table_name} WHERE resource_type = :resource_type AND #{scope_type_query(scopeable)} )) diff --git a/spec/models/rating/update_rating_spec.rb b/spec/models/rating/update_rating_spec.rb index d339580..1dc8992 100644 --- a/spec/models/rating/update_rating_spec.rb +++ b/spec/models/rating/update_rating_spec.rb @@ -4,9 +4,9 @@ require 'rails_helper' require 'support/shared_context/with_database_records' RSpec.describe Rating::Rating, ':update_rating' do - include_context 'with_database_records' - context 'with no scopeable' do + include_context 'with_database_records' + it 'updates the rating data of the given resource' do record = described_class.find_by(resource: article_1) @@ -18,6 +18,8 @@ RSpec.describe Rating::Rating, ':update_rating' do end context 'with scopeable' do + include_context 'with_database_records' + it 'updates the rating data of the given resource respecting the scope' do record = described_class.find_by(resource: article_1, scopeable: category) @@ -27,4 +29,20 @@ RSpec.describe Rating::Rating, ':update_rating' do expect(record.total).to eq 2 end end + + context 'when rate table has no record' do + let!(:resource) { create :article } + let!(:scope) { nil } + + it 'calculates with counts values as zero' do + described_class.update_rating resource, scope + + record = described_class.last + + expect(record.average).to eq 0 + expect(record.estimate).to eq 0 + expect(record.sum).to eq 0 + expect(record.total).to eq 0 + end + end end