Skip to content

Commit

Permalink
change: Replace ArgumentError with custom errors
Browse files Browse the repository at this point in the history
  • Loading branch information
pgaspar committed Oct 19, 2018
1 parent 406dcdd commit cb7ff87
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 5 deletions.
11 changes: 10 additions & 1 deletion exercises/change/.meta/generator/change_case.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,23 @@
class ChangeCase < Generator::ExerciseCase
def workload
if error_expected?
assert_raises(ArgumentError, subject_of_test)
handle_errors
else
assert_equal(expected, subject_of_test)
end
end

private

def handle_errors
case test_name
when 'test_cannot_find_negative_change_values'
assert_raises('Change::NegativeTargetError', subject_of_test)
else
assert_raises('Change::ImpossibleCombinationError', subject_of_test)
end
end

def subject_of_test
"Change.generate(#{coins}, #{target})"
end
Expand Down
6 changes: 5 additions & 1 deletion exercises/change/.meta/solutions/change.rb
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
class Change
attr_reader :coins, :target

class NegativeTargetError < ArgumentError; end
class ImpossibleCombinationError < StandardError; end

def initialize(coins, target)
@coins = coins.sort.reverse
@target = target
@total_change = []
end

def generate
raise NegativeTargetError if target.negative?
return [] if target.zero?

calculate_change(coins, [], target)
raise ArgumentError if total_change.none?
raise ImpossibleCombinationError if total_change.none?

total_change.sort
end
Expand Down
6 changes: 3 additions & 3 deletions exercises/change/change_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,21 +45,21 @@ def test_no_coins_make_0_change

def test_error_testing_for_change_smaller_than_the_smallest_of_coins
skip
assert_raises(ArgumentError) do
assert_raises(Change::ImpossibleCombinationError) do
Change.generate([5, 10], 3)
end
end

def test_error_if_no_combination_can_add_up_to_target
skip
assert_raises(ArgumentError) do
assert_raises(Change::ImpossibleCombinationError) do
Change.generate([5, 10], 94)
end
end

def test_cannot_find_negative_change_values
skip
assert_raises(ArgumentError) do
assert_raises(Change::NegativeTargetError) do
Change.generate([1, 2, 5], -5)
end
end
Expand Down

0 comments on commit cb7ff87

Please sign in to comment.