Question

Say I have a test

describe "import stuff"
  it "should import correctly"
     imported_count = import_stuff()
     assert_equal 3, imported_count
  end
end

How do I log the database state e.g. puts ImportedStuff.all.to_json when the test fails?

I know I can specify the error message like this assert_equals 3, imported_count, 'my message'. But I don't want to invoke ImportedStuff.all.to_json when the tests succeed. assert_equals seems to only accept a string for the error message.

Was it helpful?

Solution

Although it doesn't appear to be documented you can pass a Proc as a message. The proc passed will be invoked only on failure.

Example:

def print_db_state
  Proc.new { puts DimensionType.all.to_json }
end

describe "import stuff"
  it "should import correctly"
     imported_count = import_stuff()
     assert_equal 3, imported_count, print_db_state
  end
end

Passing ImportedStuff.all.to_json will invoke all.to_json every time the assertion is executed even if the test doesn't fail - not good.

OTHER TIPS

Minitest prints passed message only if assertion had failed ( https://github.com/seattlerb/minitest/blob/master/lib/minitest/assertions.rb#L127 ). You can pass "ImportedStuff.all.to_json" and don't afraid that it would be calculated for successful assertion.

You could also pass a parameterless Proc to all minitest assertions as message ( instead of String ), it would be called when test fails and it's result would be printed as message.

You usually don't need to log the database status for a test. Tests help you determine if everything is ok, or if there's something that needs your attention. If the test fails, then you can always re-run it adding a log for the database.

If you want the log to be there, I'd say to add an if:

imported_count = import_stuff()
if imported_count==3
 puts ImportedStuff.all.to_json
end
assert_equal 3, imported_count

Another option you have, is to put the logging in an after block.

EDIT

If you want to log your errors if your test fails, you can add:

def teardown
  unless passed?
    puts ImportedStuff.all.to_json
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top