From aa99f909a637bfb273ecd2d9cc753a162cb918de Mon Sep 17 00:00:00 2001 From: Tymm Schmitke Date: Tue, 19 May 2020 22:24:37 -0400 Subject: [PATCH 1/2] Add uniqueness tests for Event scope on Vote model with User association --- app/models/vote.rb | 2 ++ spec/models/vote_spec.rb | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 spec/models/vote_spec.rb diff --git a/app/models/vote.rb b/app/models/vote.rb index 2ce0e671..64ab74de 100644 --- a/app/models/vote.rb +++ b/app/models/vote.rb @@ -4,6 +4,8 @@ class Vote < ApplicationRecord belongs_to :user belongs_to :event + validates :user_id, uniqueness: { scope: :event_id } + has_paper_trail ignore: [:updated_at], meta: { conference_id: :conference_id } delegate :name, to: :user diff --git a/spec/models/vote_spec.rb b/spec/models/vote_spec.rb new file mode 100644 index 00000000..36d4d925 --- /dev/null +++ b/spec/models/vote_spec.rb @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +require 'spec_helper' + +describe Vote do + let!(:vote) { create(:vote) } + + describe 'validation' do + it 'has a valid factory' do + expect(build(:vote)).to be_valid + end + + it { is_expected.to validate_uniqueness_of(:user_id).scoped_to(:event_id) } + + # This is testing the relationship instead of using the shoulda-matchers + context 'vote with user already exists' do + it 'fails when adding vote twice for user and event' do + expect { create(:vote, user: vote.user, event: vote.event) } + .to raise_error(ActiveRecord::RecordInvalid, 'Validation failed: User has already been taken') + end + end + end +end \ No newline at end of file From 40036899b36b9b7e335bd45b1a590c894d73cbc4 Mon Sep 17 00:00:00 2001 From: Tymm Schmitke Date: Tue, 19 May 2020 23:18:05 -0400 Subject: [PATCH 2/2] Add empty line at end of file --- spec/models/vote_spec.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/models/vote_spec.rb b/spec/models/vote_spec.rb index 36d4d925..39afb352 100644 --- a/spec/models/vote_spec.rb +++ b/spec/models/vote_spec.rb @@ -20,4 +20,4 @@ describe Vote do end end end -end \ No newline at end of file +end