diff --git a/lib/rambling/trie/nodes/raw.rb b/lib/rambling/trie/nodes/raw.rb index 95f8a984..b9c6ca4b 100644 --- a/lib/rambling/trie/nodes/raw.rb +++ b/lib/rambling/trie/nodes/raw.rb @@ -11,7 +11,7 @@ class Raw < Rambling::Trie::Nodes::Node # @note This method clears the contents of the chars variable. def add chars if chars.empty? - terminal! + terminal! unless root? else add_to_children_tree chars end diff --git a/spec/lib/rambling/trie/container_spec.rb b/spec/lib/rambling/trie/container_spec.rb index 7b4aae55..e0717489 100644 --- a/spec/lib/rambling/trie/container_spec.rb +++ b/spec/lib/rambling/trie/container_spec.rb @@ -34,6 +34,12 @@ expect(root.children.size).to eq 1 expect(root.to_a).to eq %w(hello) end + + it 'does nothing with empty strings' do + add_word container, '' + expect(root.children.size).to eq 0 + expect(root.to_a).to be_empty + end # rubocop:enable RSpec/MultipleExpectations end diff --git a/spec/lib/rambling/trie/nodes/raw_spec.rb b/spec/lib/rambling/trie/nodes/raw_spec.rb index a4610bb6..142594c0 100644 --- a/spec/lib/rambling/trie/nodes/raw_spec.rb +++ b/spec/lib/rambling/trie/nodes/raw_spec.rb @@ -32,6 +32,22 @@ def assign_letter letter end describe '#add' do + context 'when the node has no parent' do + before { node.parent = nil } + + context 'when adding an empty string' do + before { add_word node, '' } + + it 'does not add new children' do + expect(node.children.size).to eq 0 + end + + it 'does not mark itself as terminal' do + expect(node).not_to be_terminal + end + end + end + context 'when the node has no branches' do before { add_word node, 'abc' } diff --git a/spec/lib/rambling/trie/stringifyable_spec.rb b/spec/lib/rambling/trie/stringifyable_spec.rb index d3677e4a..0a82c89b 100644 --- a/spec/lib/rambling/trie/stringifyable_spec.rb +++ b/spec/lib/rambling/trie/stringifyable_spec.rb @@ -4,7 +4,8 @@ describe Rambling::Trie::Stringifyable do describe '#as_word' do - let(:node) { Rambling::Trie::Nodes::Raw.new } + let(:parent) { Rambling::Trie::Nodes::Raw.new } + let(:node) { Rambling::Trie::Nodes::Raw.new nil, parent } context 'with an empty node' do before { add_word node, '' } @@ -12,6 +13,13 @@ it 'returns nil' do expect(node.as_word).to be_empty end + + context 'with no parent' do + let(:parent) { nil } + it 'returns nil' do + expect(node.as_word).to be_empty + end + end end context 'with one letter' do