Skip to content

Instantly share code, notes, and snippets.

@starkcoffee
Last active August 29, 2015 14:10
Show Gist options
  • Save starkcoffee/fbc8b0f3613fd71af710 to your computer and use it in GitHub Desktop.
Save starkcoffee/fbc8b0f3613fd71af710 to your computer and use it in GitHub Desktop.
Implementing our own 'expect' test function using blocks
# here's a function which raises an error for some cases
def sum(a,b)
if a < 0 || b < 0
raise ArgumentError, "both arguments must be greater than zero"
end
a + b
end
# here's a test function which can be used to check whether a block gives a
# expected result, OR whether it raises an error of an expected type/class
def expect(code_to_be_executed, expected)
begin
actual = code_to_be_executed.call
actual == expected
rescue => e
e.class == expected
end
end
puts "Expecting block to raise an error"
result = expect(proc{ sum(-1, 0) }, ArgumentError)
puts result
puts "Expecting block to raise an error, but we specify the wrong type of error"
result = expect(proc{ sum(-1, 0) }, StandardError)
puts result
puts "Expecting block to correctly do the sum"
result = expect(proc{ sum(1, 1) }, 2)
puts result
# in the definition of the expect function, I specified the first parameter to be a
# block. but ruby has a special feature: you can pass a block to a function
# AFTER the list of parameters, and then you can call the block within your
# using the keyword "yield". let's improve our original expect function to take
# advantage of this ruby feature. look at the two versions and observe the difference:
def expect2(expected)
begin
actual = yield
actual == expected
rescue => e
e.class == expected
end
end
# expect2 does the same thing as expect, but look at the differences
# in how we pass the block to it:
puts "Expecting block to raise an error using expect2"
result = expect2(ArgumentError) { sum(-1, 0) }
puts result
puts "Expecting block to correctly do the sum using expect2"
result = expect2(2) { sum(1, 1) }
puts result
# remember the curly braces { } are the same as "do" and "end", so this is equivalent:
puts "Expecting block to raise an error using do/end"
result = expect2(ArgumentError) do
sum(-1, 0)
end
puts result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment