Question

I am working with a custom testing framework and we are trying to expand some of the assert functionality to include a custom error message if the assert fails. The current assert is called like this:

assert_compare(first_term, :neq, second_term) do
  puts 'foobar'
end

and we want something with the functionality of:

assert_compare(first_term, :neq, second_term, error_message) do
  puts 'foobar'
end

so that if the block fails the error message will describe the failure. I think this is ugly, however, as the framework we are moving away from did this and i have to go through a lot of statements that look like:

assert.compare(variable_foo['ARRAY1'][2], variable_bar['ARRAY2'][2], 'This assert failed because someone did something unintelligent when writing the test. Probably me, since in am the one writing this really really long error statement on the same line so that you have to spend a quarter of your day scrolling to the side just to read it')

This type of method call makes it difficult to read, even when using a variable for the error message. I feel like a better way should be possible.

assert_compare(first_term, :neq, second_term) do
  puts 'foobar'
end on_fail: 'This is a nice error message'

This, to me, is the best way to do it but i don't know how or if it is even possible to accomplish this in ruby.

The goal here is to make it as aesthetic as possible. Any suggestions?

Was it helpful?

Solution

You could make on_fail a method of whatever assert_compare returns and write

assert_compare(first_term, :neq, second_term) do
  puts 'foobar'
end.on_fail: 'This is a nice error message'

OTHER TIPS

In short, no. Methods in ruby take a block as the final parameter only. As Chuck mentioned you could attempt to make the on_fail method a method of whatever assert_compare returns and that is a good solution. The solution I've come up with is not what you are looking for, but it works:

def test block, param
  block.call
  puts param
end

test proc { puts "hello"}, "hi"

will result in

"hello"
"hi"

What I've done here is create a Proc (which is essentially a block) and then passed it as a regular parameter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top