Skip to content

Commit

Permalink
Setup seperate error classes for each case
Browse files Browse the repository at this point in the history
  • Loading branch information
schneiderderek authored and Derek Schneider committed Jun 23, 2016
1 parent 7f8faa8 commit 0cb32b5
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 11 deletions.
21 changes: 14 additions & 7 deletions lib/first_and_only.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,22 @@

module Enumerable
def first_and_only!
fail(FirstAndOnly::CountNotOne.new) if first(2).count != 1
first
case first(2).count
when 0
fail FirstAndOnly::CountZero, FirstAndOnly::COUNT_ZERO_ERROR_MESSAGE
when 1
first
else
fail FirstAndOnly::CountGreaterThanOne, FirstAndOnly::COUNT_GREATER_THAN_ONE_ERROR_MESSAGE
end
end

module FirstAndOnly
class CountNotOne < StandardError
def initialize
super("Expected the count to be 1.")
end
end
CountNotOne = Class.new(StandardError)
CountZero = Class.new(CountNotOne)
CountGreaterThanOne = Class.new(CountNotOne)

COUNT_ZERO_ERROR_MESSAGE = 'Expected the count to be 1, was 0.'.freeze
COUNT_GREATER_THAN_ONE_ERROR_MESSAGE = 'Expected the count to be 1, was greater than 1.'.freeze
end
end
8 changes: 4 additions & 4 deletions spec/first_and_only_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
shared_examples_for "it_is_empty" do
specify do
expect { subject.first_and_only! }.to raise_error(
Enumerable::FirstAndOnly::CountNotOne,
"Expected the count to be 1."
Enumerable::FirstAndOnly::CountZero,
"Expected the count to be 1, was 0."
)
end
end
Expand All @@ -20,8 +20,8 @@
fail "bad example" if subject.first(2).count < 2

expect { subject.first_and_only! }.to raise_error(
Enumerable::FirstAndOnly::CountNotOne,
"Expected the count to be 1."
Enumerable::FirstAndOnly::CountGreaterThanOne,
"Expected the count to be 1, was greater than 1."
)
end
end
Expand Down

0 comments on commit 0cb32b5

Please sign in to comment.