fix: avoid error when has no rate record

main
Washington Botelho 2018-02-08 18:37:13 -02:00
parent 1525a7b95f
commit e29e0c049e
No known key found for this signature in database
GPG Key ID: 5DE4F42A8F073617
2 changed files with 21 additions and 3 deletions

View File

@ -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)}
))

View File

@ -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