!Mac OS X-10.15.7 !ruby-2.6.3p62
assert_equal
今回の題材はテスト駆動用の根幹となる, assert_equalです.まずは1==1から始めてみます.
code
p 1==1
結果
> ruby assert_equal.rb
true
これをテスト用のメソッドに置き換えると,
def assert_equal(expected, result)
return expected == result
end
p assert_equal(1, 1)
Colorize
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)
出力結果が, 緑や赤に変化した.
Richer output
出力をもう少し見やすくする.
require 'colorize'
def assert_equal(expected, result)
puts "expected :: #{expected}"
puts "result :: #{result}"
if expected == result
puts "succeeded in assert_equal".green
else
puts 'failed in assert_equal'.red
end
end
assert_equal(1,1)
assert_equal(1,2)
clear code
重複している箇所を個別に分けて関数に書き換える.
require 'colorize'
def puts_vals(expected, result)
puts "expected :: #{expected}"
puts "result :: #{result}"
end
def assert_equal(expected, result)
puts_vals(expected,result)
if expected == result
puts "succeeded in assert_equal".green
else
puts 'failed in assert_equal'.red
end
end
重複実行の予防
require './assert_equal'
assert_equal(2, 1*2)
assert_not_equal('bob', 'bob2')
しかし, 今のままだと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
これを踏まえて, まとめると以下のようになる.以下の内容は覚えておく!!
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
if $PROGRAM_NAME == __FILE__
assert_equal(1, 1)
assert_equal(1, 2)
assert_not_equal(1, 2)
assert_not_equal(1, 1)
end
参考サイト
https://qiita.com/daddygongon/items/f6cea87314ee26e130eahttps://qiita.com/Mutakouki7595/items/1f3e59fad4aa187a7431
- source ~/my_ruby/grad_members_20f/members/drop-sd/lectures/no9.org