From 673e12c052fc2b61235b58a4eae7c76b924859eb Mon Sep 17 00:00:00 2001 From: Thor77 Date: Tue, 20 Nov 2018 16:03:58 +0100 Subject: [PATCH] Validate Stage xor Group present in match --- app/models/match.rb | 12 ++++++++++-- spec/factories/matches.rb | 5 ++++- spec/models/match_spec.rb | 17 +++++++++++++++++ 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/app/models/match.rb b/app/models/match.rb index 54c1f66..39aec8a 100644 --- a/app/models/match.rb +++ b/app/models/match.rb @@ -1,9 +1,17 @@ # frozen_string_literal: true class Match < ApplicationRecord - belongs_to :stage - belongs_to :group + belongs_to :stage, optional: true + belongs_to :group, optional: true has_many :scores, dependent: :destroy validates :scores, length: { maximum: 2 } + + validate :stage_xor_group + + private + + def stage_xor_group + errors.add(:stage_xor_group, 'Stage and Group missing or both present') unless stage.present? ^ group.present? + end end diff --git a/spec/factories/matches.rb b/spec/factories/matches.rb index 55e26c3..5c8b5a6 100644 --- a/spec/factories/matches.rb +++ b/spec/factories/matches.rb @@ -1,8 +1,11 @@ # frozen_string_literal: true FactoryBot.define do - factory :match do + factory :stage_match, aliases: [:match], class: Match do stage + end + + factory :group_match, class: Match do group end end diff --git a/spec/models/match_spec.rb b/spec/models/match_spec.rb index 1162808..7eb6c67 100644 --- a/spec/models/match_spec.rb +++ b/spec/models/match_spec.rb @@ -9,6 +9,23 @@ RSpec.describe Match, type: :model do it { should belong_to :group } end + context '#new' do + it 'needs only a group' do + match = Match.new group: build(:group) + expect(match).to be_valid + end + + it 'needs only a stage' do + match = Match.new stage: build(:stage) + expect(match).to be_valid + end + + it 'can\'t have a group and a stage' do + match = Match.new group: build(:group), stage: build(:stage) + expect(match).to be_invalid + end + end + context 'scores' do before do @match = create(:match)