require 'spec_helper' module Flydata module Util describe FileUtil do subject { Class.new { include FileUtil }.new } let(:file_path) { Tempfile.new('helper_rspec_one_line_file').path } let(:dummy_content) { 'dummy_content' } before do FileUtils.rm(file_path) if File.exists?(file_path) end describe "#tail" do shared_examples 'tail and retrieves correct number of lines' do before do File.open(file_path,'w') do |io| 1.upto(total_line_count) do |i| io.write("line#{i}\n") end end end it "returns expected lines" do tailed_lines = subject.tail(file_path, tailed_line_count) expect(tailed_lines.count("\n")).to eq(expected_line_range.size) expected_line_range.each do |i| expect(tailed_lines).to include("line#{i}\n") end end end context "when the tailed file has less lines than the passed parameter" do let(:total_line_count) { 10 } let(:tailed_line_count) { 100 } let(:expected_line_range) { 1..10 } include_examples 'tail and retrieves correct number of lines' end context "when the tailed file has equal number of lines as the passed parameter" do let(:total_line_count) { 10 } let(:tailed_line_count) { 10 } let(:expected_line_range) { 1..10 } include_examples 'tail and retrieves correct number of lines' end context "when the tailed file has greater number of lines than the passed parameter" do let(:total_line_count) { 100 } let(:tailed_line_count) { 10 } let(:expected_line_range) { 91..100 } include_examples 'tail and retrieves correct number of lines' end context "when the tailed file is empty" do before do File.open(file_path,'w').write("") end it "returns an empty string" do expect(subject.tail(file_path, 10)).to eq("") end end end describe "#write_line" do context 'when file does not exist' do it 'creates the file' do subject.write_line(file_path, dummy_content) expect(IO.read(file_path)).to eq(dummy_content) end end context 'when the file exists' do it 'overwrites file' do IO.write(file_path, "aaaa\nbbbb\nccc\n") subject.write_line(file_path, dummy_content) expect(IO.read(file_path)).to eq(dummy_content) end end end describe "#read_line" do let(:default_value) { nil } context 'when file does not exist' do it 'return nil' do expect(subject.read_line(file_path, nil)).to be_nil end end context 'when file exists' do before do subject.write_line(file_path, dummy_content) end it 'return first line of content' do expect(subject.read_line(file_path, nil)).to eq(dummy_content) end end context 'when file is empty' do before do subject.write_line(file_path, '') end it 'return empty string' do expect(subject.read_line(file_path, nil)).to eq('') end end end end end end