なんとな~くしあわせ?の日記

「そしてそれゆえ、知識そのものが力である」 (Nam et ipsa scientia potestas est.) 〜 フランシス・ベーコン

RSpecでファイル読み書きテストをやる

Rubyには Tempfile というクラスがあるので、それを使えばOK

  • Ruby 2.4で試してます
  • File.read するときはエンコード指定したほうがよいかも

class Tempfile (Ruby 2.5.0)

RSpec.describe ModuleXXX do

  before(:all) do
    @module = ModuleXXX.new
  end

  context " ファイルパターン1について(pattern1.txt)" do
    #File.open(File.expand_path('test.txt'), "w", 0755) do |f|
    Tempfile.create("test.txt") do |f|
      it " は出力に欠損がない " do
        # 一時ファイルでテスト
        file1 = FILE_PATH_TO_TEST
        file2 = f.path

        @modul.exec(["--input",
                  "#{file1}",
                  "--output",
                  "#{file2}"])

      end

      it ' 処理後のファイルの行数は 8' do
        expect(File.read(f.path, encoding: 'cp932').count("\n")).to eq(8)
      end

    end

    GC.enable
  end