How do I report all failures after completing the entire test?
I am using Ruby 1.9.3 with MiniTest. I know the best practice is to have one assertion per test, but there are times when I want to make assertions dynamically, for example when comparing arrays:
if added_skus.each { |s| assert(skus_in_cart.include?(s), "SKUs #{added_skus} or SKU amount do not match SKUs #{skus_in_cart} on Cart page.") }
puts "Product SKUs #{added_skus} match SKUs #{skus_in_cart} on Cart page."
end
As you know, when it reaches the first assertion rejection, the test ends. I would like to continue with the test and report all failures after the test completes.
I found a solution using old test / unit and Ruby 1.8.7 (add_failure method in test / unit library) but I can't find a good solution for MiniTest and Ruby 1.9.3. I'd really appreciate some feedback (even if it means I'm doing it wrong - please point me in the right direction). Thank you!
source to share
Solution 1 - Combine statements into one statement:
You can write your current code as one statement, considering all skus together:
#Determine the missing skus:
missing_skus = added_skus.find_all{ |s| not(skus_in_cart.include?(s)) }
#Assert that there are no missing skus:
assert( missing_skus.empty?, "SKUs #{missing_skus} do not match SKUs on Cart page." )
Solution 2 - Custom method to approve multiple items:
If you really want the number of claims to match an individual SKU (instead of the entire set), you could create your own claim method. Although I don't believe this adds any real benefit over solution 1.
Sample code:
requires "test / unit"
module MiniTest::Assertions
#Asserts that each element passes the test
# Inputs:
# enumerable - The object to iterate over (ex an array)
# msg - Custom message to include in assertion failure
# test - A block that each element will be tested against
def assert_each(enumerable, msg = nil, &test)
msg ||= "No message given."
failed_elements = Array.new
enumerable.each do |e|
self._assertions += 1
failed_elements << e unless yield(e)
end
msg = " #{failed_elements} failed assertion. #{msg}"
raise( MiniTest::Assertion, msg ) unless failed_elements.empty?
end
end
class MyTest < Test::Unit::TestCase
def test()
added_skus = ['b', 'a', 'c', 'd']
skus_in_cart = ['c', 'b']
assert_each(added_skus, "SKUs missing from cart."){ |s| skus_in_cart.include?(s) }
end
end
source to share