2

More than 1 year has passed since last update.

# assert_equalを作って簡単にテストを書けるようにする

Last updated at Posted at 2020-12-29

# Preface (はじめに)

テスト駆動型開発(TDD)では簡易的なテストを何度も繰り返し開発を進めることが基本です.

# Assert

## Equal

まずは`expected``result`の値が等しいか確かめる

assert_equal.rb
``````def assert_equal(expected, result)
return expected == result
end

p assert_equal(1, 1)
``````
``````> ruby assert_equal.rb
-> true
``````

assert_equal.rb
``````require 'colorize'

def assert_equal(expected, result)
if expected == result
puts 'true'.green
else
puts 'false'.red
end
end

assert_equal(1, 1)
assert_equal(1, 2)
``````

• 引数のexpectedとresultの値を出力
• 先ほどのassert_equalの処理を以下のように変更
• true: print "succeeded in assert_equal.\n".green
• false: print "failed in assert_equal.\n".red
assert_equal.rb
``````require 'colorize'

def puts_vals(expected, result)
puts "expected :: #{expected}"
puts "result   :: #{result}"
end
def assert_equal(expected, result)
puts_vals(expected, result)
print  case expected == result
when true  ; "succeeded in #{__method__}.\n".green
when false ; "failed in #{__method__}.\n".red
end
end

assert_equal(1, 1)
assert_equal(1, 2)
``````

``````> ruby assert_equal.rb
``````
``````expected :: 1
result   :: 1
succeeded in assert_equal.
expected :: 1
result   :: 2
failed in assert_equal.
``````

となります. (Qiita上では色は変わっていません.)

## Not Equal

assert_equal.rb
``````require 'colorize'

def puts_vals(expected, result)
puts "expected :: #{expected}"
puts "result   :: #{result}"
end
def assert_not_equal(expected, result)
puts_vals(expected, result)
print expected != result ?
"succeeded in #{__method__}.\n".green :
"failed in #{__method__}.\n".red
end
def assert_equal(expected, result)
puts_vals(expected, result)
print  case expected == result
when true  ; "succeeded in #{__method__}.\n".green
when false ; "failed in #{__method__}.\n".red
end
end

assert_equal(1, 1)
assert_equal(1, 2)
assert_not_equal(1, 2)
assert_not_equal(1, 1)
``````

``````> ruby assert_equal.rb
``````
``````expected :: 1
result   :: 1
succeeded in assert_equal.
expected :: 1
result   :: 2
failed in assert_equal.
expected :: 1
result   :: 2
succeeded in assert_not_equal.
expected :: 1
result   :: 1
failed in assert_not_equal.
``````

このassert_equalやassert_not_equalは便利なので他のコードにも使いたいです. しかしこのままでは, コード内のテストも実行されてしまうので,

assert_equal.rb
``````if \$PROGRAM_NAME == __FILE__
assert_equal(1, 1)
assert_equal(1, 2)
assert_not_equal(1, 2)
assert_not_equal(1, 1)
end
``````

というようにテスト部分を変えます.
このように書くことでcodeが書いてあるファイル名(＿FILE＿)とPROGRAMが動いているファイル名(\$PROGRAM_FILE)とが一致したら, 中身を実行するようにできます.

# 参考資料

チャート式ruby-IV(assert_equal)

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
What you can do with signing up
2