From 2ce10af051db7115d9b305c124a6c16d0c5b382f Mon Sep 17 00:00:00 2001 From: Christian Mehlmauer Date: Sun, 8 Dec 2013 01:28:19 +0100 Subject: [PATCH] rspecs --- lib/common/common_helper.rb | 8 ++- spec/lib/common/common_helper_spec.rb | 81 ++++++++++++++++++++++++++- 2 files changed, 85 insertions(+), 4 deletions(-) diff --git a/lib/common/common_helper.rb b/lib/common/common_helper.rb index c3647108..4f0a1cca 100644 --- a/lib/common/common_helper.rb +++ b/lib/common/common_helper.rb @@ -180,7 +180,9 @@ end # Truncates a string to a specific length and adds ... at the end def truncate(input, size, trailing = '...') - padded_length = size - trailing.length - 2 # ... + space + index 0 - return input if input.nil? or size <= trailing.length or size <= 0 or input.length <= size - return "#{input[0...padded_length]}#{trailing}" + size = size.to_i + trailing ||= '' + return input if input.nil? or size <= 0 or input.length <= size or + trailing.length >= input.length or size-trailing.length-1 >= input.length + return "#{input[0..size-trailing.length-1]}#{trailing}" end diff --git a/spec/lib/common/common_helper_spec.rb b/spec/lib/common/common_helper_spec.rb index 17c98063..a423a573 100644 --- a/spec/lib/common/common_helper_spec.rb +++ b/spec/lib/common/common_helper_spec.rb @@ -88,4 +88,83 @@ describe 'common_helper' do @expected = @html end end -end \ No newline at end of file + + describe '#truncate' do + after :each do + output = truncate(@input, @length, @trailing) + output.should == @expected + end + + it 'returns nil on no input' do + @input = nil + @length = 1 + @expected = nil + @trailing = '...' + end + + it 'returns input when length > input' do + @input = '1234567890' + @length = 13 + @expected = @input + @trailing = '...' + end + + it 'truncates the input' do + @input = '1234567890' + @length = 6 + @expected = '123...' + @trailing = '...' + end + + it 'adds own trailing' do + @input = '1234567890' + @length = 7 + @expected = '123xxxx' + @trailing = 'xxxx' + end + + it 'accepts strings as length' do + @input = '1234567890' + @length = '6' + @expected = '123...' + @trailing = '...' + end + + it 'checks if trailing is longer than input' do + @input = '1234567890' + @length = 1 + @expected = @input + @trailing = 'A' * 20 + end + + it 'returns input on negative length' do + @input = '1234567890' + @length = -1 + @expected = @input + @trailing = '...' + end + + it 'returns input on length == input.length' do + @input = '1234567890' + @length = '10' + @expected = @input + @trailing = '...' + end + + it 'returns cut string on nil trailing' do + @input = '1234567890' + @length = 9 + @expected = '123456789' + @trailing = nil + end + + it 'trailing.length > length' do + @input = '1234567890' + @length = 1 + @expected = @input + @trailing = 'A' * 20 + end + + end + +end