Chart type ruby-IV (assert \ _equal)
Let's create a function assert \ _equal that checks if two variables are equal
When simply implemented, it looks like this
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
The output result looks like this
["expected", 1]
["result", 1]
true
["expected", 1]
["result", 2]
false
You can change the font color with colorize Because the output result of this page is just copied and pasted from the terminal The color is not reflected, but the text color is the output result in the terminal true is green and false is red
If you get angry that there is no colorize, install it
> gem install colorize
EX
Add assert \ _not \ _equal that returns the opposite result of assert \ _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
The execution result is as follows
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 will be used repeatedly in the future If you write if $ PROGRAM \ _NAME == \ _ \ _ FILE \ _ \ _ in the test part, the operation enclosed in this part will be Stops executing when called from an external file How to call it next time
Recommended Posts