Skip to content

Commit

Permalink
Fix bug in Mutant::Util.one
Browse files Browse the repository at this point in the history
  • Loading branch information
mbj committed May 12, 2024
1 parent b928205 commit 8d08afe
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 25 deletions.
9 changes: 6 additions & 3 deletions lib/mutant/util.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@ module Util
#
# @return [Object] first entry
def self.one(array)
return array.first if array.one?

fail SizeError, "expected size to be exactly 1 but size was #{array.size}"
case array
in [value]
value
else
fail SizeError, "expected size to be exactly 1 but size was #{array.size}"
end
end
end # Util
end # Mutant
22 changes: 0 additions & 22 deletions spec/unit/mutant/util/one_spec.rb

This file was deleted.

55 changes: 55 additions & 0 deletions spec/unit/mutant/util_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# frozen_string_literal: true

RSpec.describe Mutant::Util, '.one' do
let(:item) { instance_double(Object) }

def apply
described_class.one(array)
end

context 'when array has exactly one element' do
context 'and that element is nil' do
let(:array) { [nil] }

it 'returns nil' do
expect(apply).to be(nil)
end
end

context 'and that element is false' do
let(:array) { [false] }

it 'returns false' do
expect(apply).to be(false)
end
end

context 'and that element is a regular object' do
let(:array) { [item] }

it 'returns first element' do
expect(apply).to be(item)
end
end
end

context 'when array is empty' do
let(:array) { [] }

it 'raises expected error' do
expect { apply }
.to raise_error(described_class::SizeError)
.with_message('expected size to be exactly 1 but size was 0')
end
end

context 'when array has more than one element' do
let(:array) { [1, 2] }

it 'raises expected error' do
expect { apply }
.to raise_error(described_class::SizeError)
.with_message('expected size to be exactly 1 but size was 2')
end
end
end

0 comments on commit 8d08afe

Please sign in to comment.