diff --git a/app/models/tournament.rb b/app/models/tournament.rb index 3813f08..ec71609 100644 --- a/app/models/tournament.rb +++ b/app/models/tournament.rb @@ -10,6 +10,8 @@ class Tournament < ApplicationRecord validates :name, presence: true validates :code, presence: true, uniqueness: true + validate :playoff_teams_amount_is_positive_power_of_two + alias_attribute :owner, :user after_initialize :generate_code @@ -24,4 +26,11 @@ class Tournament < ApplicationRecord break if errors['code'].blank? end end + + def playoff_teams_amount_is_positive_power_of_two + return if (Utils.po2?(playoff_teams_amount) && playoff_teams_amount.positive?) || playoff_teams_amount.zero? + + errors.add(:playoff_teams_amount, + 'playoff_teams_amount needs to be a positive power of two') + end end diff --git a/db/migrate/0000_create_schema.rb b/db/migrate/0000_create_schema.rb index 14ffb52..390edfa 100644 --- a/db/migrate/0000_create_schema.rb +++ b/db/migrate/0000_create_schema.rb @@ -51,7 +51,7 @@ class CreateSchema < ActiveRecord::Migration[5.2] t.string :code, null: false, index: { unique: true } t.string :description t.boolean :public, default: true - t.integer :playoff_teams_amount + t.integer :playoff_teams_amount, default: 0 t.integer :instant_finalists_amount, default: 0 t.integer :intermediate_round_participants_amount, default: 0 diff --git a/spec/controllers/tournaments_controller_spec.rb b/spec/controllers/tournaments_controller_spec.rb index c3313bd..c0e1353 100644 --- a/spec/controllers/tournaments_controller_spec.rb +++ b/spec/controllers/tournaments_controller_spec.rb @@ -194,6 +194,29 @@ RSpec.describe TournamentsController, type: :controller do expect(@group_stage_tournament.playoff_teams_amount) .to eq(create_group_tournament_data[:playoff_teams_amount]) end + + context 'playoff_teams_amount unacceptable' do + it 'is not a power of two' do + post :create, params: create_group_tournament_data.merge(playoff_teams_amount: 18) + expect(response).to have_http_status(:unprocessable_entity) + expect(deserialize_response(response).values.first.first) + .to eq('playoff_teams_amount needs to be a positive power of two') + end + + it 'isn\'t positive' do + post :create, params: create_group_tournament_data.merge(playoff_teams_amount: -16) + expect(response).to have_http_status(:unprocessable_entity) + expect(deserialize_response(response).values.first.first) + .to eq('playoff_teams_amount needs to be a positive power of two') + end + + it 'isn\'t positive nor a power of two' do + post :create, params: create_group_tournament_data.merge(playoff_teams_amount: -42) + expect(response).to have_http_status(:unprocessable_entity) + expect(deserialize_response(response).values.first.first) + .to eq('playoff_teams_amount needs to be a positive power of two') + end + end end it 'renders a JSON response with the new tournament' do