diff --git a/app/models/snapshot.rb b/app/models/snapshot.rb index 3fbe9c4..5bdaa00 100644 --- a/app/models/snapshot.rb +++ b/app/models/snapshot.rb @@ -11,6 +11,7 @@ class Snapshot end def crop(width, height) + height = [height, lines.size].min new_lines = lines.drop(lines.size - height).map { |line| line.crop(width) } self.class.new(new_lines) end diff --git a/spec/models/snapshot_spec.rb b/spec/models/snapshot_spec.rb index aa80f48..f1d3af0 100644 --- a/spec/models/snapshot_spec.rb +++ b/spec/models/snapshot_spec.rb @@ -23,22 +23,48 @@ describe Snapshot do describe '#crop' do let(:snapshot) { Snapshot.new(lines) } let(:lines) { [line_1, line_2, line_3] } - let(:line_1) { double('line_1', :crop => nil) } + let(:line_1) { double('line_1', :crop => cropped_line_1) } let(:line_2) { double('line_2', :crop => cropped_line_2) } let(:line_3) { double('line_3', :crop => cropped_line_3) } + let(:cropped_line_1) { double('cropped_line_1') } let(:cropped_line_2) { double('cropped_line_2') } let(:cropped_line_3) { double('cropped_line_3') } + let(:width) { 3 } - it 'crops the last "height" lines' do - snapshot.crop(3, 2) + subject { snapshot.crop(width, height) } - expect(line_1).to_not have_received(:crop) - expect(line_2).to have_received(:crop).with(3) - expect(line_3).to have_received(:crop).with(3) + context "when height is lower than lines count" do + let(:height) { 2 } + + it 'crops the last "height" lines' do + subject + + expect(line_1).to_not have_received(:crop) + expect(line_2).to have_received(:crop).with(3) + expect(line_3).to have_received(:crop).with(3) + end + + it 'returns a new Snapshot with last 2 lines cropped' do + expect(subject).to eq(Snapshot.new([cropped_line_2, cropped_line_3])) + end end - it 'returns a new Snapshot with cropped lines' do - expect(snapshot.crop(3, 2)).to eq(Snapshot.new([cropped_line_2, cropped_line_3])) + context "when height is equal to lines count" do + let(:height) { 3 } + + it 'returns a new Snapshot with all lines cropped' do + expect(subject).to eq(Snapshot.new([cropped_line_1, cropped_line_2, + cropped_line_3])) + end + end + + context "when height is greater than lines count" do + let(:height) { 4 } + + it 'returns a new Snapshot with all lines cropped' do + expect(subject).to eq(Snapshot.new([cropped_line_1, cropped_line_2, + cropped_line_3])) + end end end end