LoginSignup
10
10

More than 5 years have passed since last update.

FakefsでTest-Drivenな運用スクリプト

Last updated at Posted at 2012-12-26

この記事は最終更新から1年以上経過しています。 気をつけてね。

見せかけのFilesystemを操作して、運用系のRubyスクリプトをテストする。

FakeFS[https://github.com/defunkt/fakefs]

ディレクトリ・ファイルを操作するサンプルツール

ディレクトリを操作するメソッドを用意、屋上に屋根状態だが実際はあれこれと処理をしてから実行します。

app.rb
#!/usr/bin/env ruby
# cording: utf-8

def create_dir(dir_name)
  Dir.mkdir(dir_name)
end

def remove_dir(dir_name)
  Dir.rmdir(dir_name)
end

Fakefsを使ったテストを書く

fakefsはDirやらFile,symlinkあたりをオーバーライドして、仮想的なファイルシステム上での操作にしてくれる。

test_app.rb
#!/usr/bin/env ruby                                                                                                                                                       # cording: utf-8
require 'bundler/setup'
require 'test/unit'
require 'fakefs'

require "./app"

class AppTest < Test::Unit::TestCase

  def test_create_dir
    create_dir("hoge")
    assert Dir.exists?("hoge") 
  end

  def test_remove_dir
    Dir.mkdir("piyo")
    remove_dir("piyo")
    assert !Dir.exists?("piyo") 
  end
end

このテストでtest_create_dirの後ならディレクトリhogeが残っているはずだが、実ファイルシステム上には存在しない。

テスト実施

実行のサンプル

$ ./test_app.rb 
Run options: 

# Running tests:

..

Finished tests in 0.007162s, 279.2516 tests/s, 279.2516 assertions/s.

2 tests, 2 assertions, 0 failures, 0 errors, 0 skips

テストOK、hogepiyoも実ファイルシステム上には作られない。

10
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10