Skip to content

Commit

Permalink
Avoid calling count on Enumerable
Browse files Browse the repository at this point in the history
  • Loading branch information
schneiderderek authored and Derek Schneider committed Jun 21, 2016
1 parent f74766d commit 7f8faa8
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
6 changes: 3 additions & 3 deletions lib/first_and_only.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@

module Enumerable
def first_and_only!
fail(FirstAndOnly::CountNotOne.new count) if first(2).count != 1
fail(FirstAndOnly::CountNotOne.new) if first(2).count != 1
first
end

module FirstAndOnly
class CountNotOne < StandardError
def initialize(count)
super("Expected the count to be 1, but it was #{count}.")
def initialize
super("Expected the count to be 1.")
end
end
end
Expand Down
24 changes: 21 additions & 3 deletions spec/first_and_only_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,18 @@
specify do
expect { subject.first_and_only! }.to raise_error(
Enumerable::FirstAndOnly::CountNotOne,
"Expected the count to be 1, but it was 0."
"Expected the count to be 1."
)
end
end

shared_examples_for "it_has_more_than_one_element" do
specify do
fail "bad example" if subject.count < 2
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, but it was #{subject.count}."
"Expected the count to be 1."
)
end
end
Expand Down Expand Up @@ -76,4 +76,22 @@ def each

end

describe "infinite enumerable" do
let(:infinite_enumerable) do
Class.new do
include Enumerable

def each
yield(rand(1_000_000)) while true
end
end
end

context "with more than on element" do
subject { infinite_enumerable.new }
it_behaves_like "it_has_more_than_one_element"
end

end

end

0 comments on commit 7f8faa8

Please sign in to comment.