-
-
Save Wolwer1nE/bdae8167d04cae8181cf0b0fefc5f32f to your computer and use it in GitHub Desktop.
character.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Character < ApplicationRecord | |
TEAMS_FOR_UNITS = { | |
knight: 1, | |
mage: 1, | |
medusa: 2, | |
jinn: 2 | |
} | |
validates :team, presence: true | |
validates :unit, presence: true | |
validates :unit, acceptance: { accept: ['mage', 'knight', 'medusa', 'jinn']} | |
validate :correct_team | |
before_validation :set_team | |
private | |
def correct_team | |
errors.add(:unit, "Unit shoild match team") unless TEAMS_FOR_UNITS[unit.to_sym] == team | |
end | |
def set_team | |
self.team = TEAMS_FOR_UNITS[unit.to_sym] if self.team.nil? | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AdminUserTest < ActiveSupport::TestCase | |
def test_team_auto_select | |
character = Character.new(unit: 'knight') | |
character.save | |
assert_equal 1, character.team, 'Expected team to be auto selected' | |
end | |
def test_wrong_unit_rejected | |
character = Character.new(unit: 'sknight') | |
character.save | |
refute character.valid?, 'Character should be invalidated for wrong unit' | |
end | |
def test_wrong_team_rejected | |
character = Character.new(unit: 'knight', team: -1) | |
character.save | |
refute character.valid?, 'Character should be invalidated for wrong team' | |
end | |
def test_wrong_team_and_unit_match | |
character = Character.new(unit: 'knight', team: 2) | |
character.save | |
refute character.valid?, 'Character should be invalidated for wrong team-unit pair' | |
end | |
def test_correct_team_and_unit_match | |
character = Character.new(unit: 'medusa', team: 2) | |
character.save | |
assert character.valid?, 'Character should be saved with explicit unit-team pair' | |
assert_equal 2, character.team, 'Explicitly defined team should be present' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment