Skip to content

Instantly share code, notes, and snippets.

@a2ikm
Created March 4, 2011 05:02
Show Gist options
  • Select an option

  • Save a2ikm/854200 to your computer and use it in GitHub Desktop.

Select an option

Save a2ikm/854200 to your computer and use it in GitHub Desktop.
module CustomFileMatchers
#
# 1つのマッチャを処理するためのクラス
#
class MoveFile
def initialize(src, dest)
@src = src
@dest = dest
end
#
# xxx.should ...としたときのxxxがtrialとして与えられるので、
# これがテストに通るか否かをbooleanで返す
#
def matches?(trial)
src_digest = digest_of(@src)
unless FileTest.exist?(@src)
@error = "source file didn't exist"
return false
end
trial.call
unless !FileTest.exist?(@src)
@error = "source file still exists"
return false
end
unless FileTest.exist?(@dest)
@error = "destination file doesn't exist"
return false
end
unless src_digest == digest_of(@dest)
@error = "destination file's MD5 checksum doesn't match with source's one"
return false
end
true
end
#
# テストに通らなかったときにエラーメッセージを
# 取得するために呼ばれる
#
def failure_message_for_should
"expected #{@src} to move to #{@dest} (#{@error})"
end
private
def digest_of(path)
str = ""
File.open(path, "rb") do |f|
buf = ""
while f.read(256, buf)
str << buf
end
end
Digest::MD5.hexdigest(str)
end
end
#
# xxx.should ...の...の部分で、
# マッチャを処理するクラスをインスタンス化して返す
#
def move_file(src, dest)
MoveFile.new(src, dest)
end
end
describe CustomFileMatchers do
include CustomFileMatchers
describe "::MoveFile" do
it "should pass when a file moved" do
src = "#{RAILS_ROOT}/tmp/a.txt"
dest = "#{RAILS_ROOT}/tmp/b.txt"
FileUtils.touch src
lambda { FileUtils.mv src, dest }.should move_file(src, dest)
end
it "should NOT pass when a file didn't move" do
src = "#{RAILS_ROOT}/tmp/a.txt"
dest = "#{RAILS_ROOT}/tmp/b.txt"
FileUtils.touch src
lambda {}.should_not move_file(src, dest)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment