Validate Stage xor Group present in match

This commit is contained in:
Thor77 2018-11-20 16:03:58 +01:00
parent feee3f9378
commit 673e12c052
3 changed files with 31 additions and 3 deletions

View File

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

View File

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

View File

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