1
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.

第九回講義メモ

Last updated at Posted at 2020-12-31

!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
1
0
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
1
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?