diff --git a/app/models/course_user.rb b/app/models/course_user.rb index 9cace1717f8..06a7d4fda00 100644 --- a/app/models/course_user.rb +++ b/app/models/course_user.rb @@ -2,7 +2,13 @@ class CourseUser < ActiveRecord::Base belongs_to :user, inverse_of: :course_users belongs_to :course, inverse_of: :course_users has_many :experience_points_records, class_name: Course::ExperiencePointsRecord.name, - inverse_of: :course_user, dependent: :destroy + inverse_of: :course_user, dependent: :destroy do + def experience_points + sum(:points_awarded) + end + end enum role: { student: 0, teaching_assistant: 1, manager: 2, owner: 3 } + + delegate :experience_points, to: :experience_points_records end diff --git a/spec/factories/course_experience_points_records.rb b/spec/factories/course_experience_points_records.rb index 35c6e183994..68b6bebbec8 100644 --- a/spec/factories/course_experience_points_records.rb +++ b/spec/factories/course_experience_points_records.rb @@ -3,7 +3,7 @@ creator updater course_user - points_awarded 100 + points_awarded { rand(1..20) * 100 } reason 'EXP for some event' end end diff --git a/spec/models/course_user_spec.rb b/spec/models/course_user_spec.rb index f083b2e2241..aab19570dd9 100644 --- a/spec/models/course_user_spec.rb +++ b/spec/models/course_user_spec.rb @@ -16,4 +16,19 @@ it { is_expected.to be_student } it { is_expected.not_to be_phantom } end + + let!(:instance) { create :instance } + with_tenant(:instance) do + describe '#exp_points' do + let!(:exp_record_1) { create(:course_experience_points_record) } + let!(:exp_record_2) do + create(:course_experience_points_record, course_user: exp_record_1.course_user) + end + subject { exp_record_1.course_user } + it 'sums all associated experience points records' do + points_awarded = exp_record_1.points_awarded + exp_record_2.points_awarded + expect(subject.experience_points).to eq(points_awarded) + end + end + end end