3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

授業9回目:assert_equal

Last updated at Posted at 2020-12-24

参考サイト

チャート式ruby-IV(assert_equal)

お題:assert_equal を作ろう

2つの変数が等価(equal)かどうかを確かめる関数 assert_equal を作ろう

実装例

単純に実装するとこんな感じ

require 'colorize'

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

if $PROGRAM_NAME == __FILE__
  assert_equal(1, 1)
  assert_equal(1, 2)
end

出力結果はこんな感じ

["expected", 1]
["result", 1]
true
["expected", 1]
["result", 2]
false

colorize で文字色を変更することができる
このページの出力結果はターミナルからコピペしただけなので
色が反映されていないが、ターミナルでの出力結果は文字色が
true が緑色、false が赤色になっている

colorize なんて無ぇぞ、と怒られてしまったらインストールする

> gem install colorize

EX

assert_equal とは逆の結果を返す assert_not_equal の追加


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 #{__method__}.".green
  else
    puts "failed in #{__method__}.".red
  end
end

def assert_not_equal(expected, result)
  puts_vals(expected, result)
  if expected != result
    puts "succeeded in #{__method__}.".green
  else
    puts "failed in #{__method__}.".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

実行結果は以下の通り

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.

note

・assert_equalは今後繰り返し使うことになる
 テスト部分に if $PROGRAM_NAME == __FILE__ を記述すれば、この部分に囲われた動作は
 外部ファイルから呼び出されたときに実行しなくなる
 呼び出し方法については今度使うときに


  • source ~/grad_members_20f/members/batamon-427/task9.org
3
0
1

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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?