Capturing output with UnitTest in Ruby

Email this to someoneShare on Google+Share on FacebookTweet about this on TwitterShare on LinkedIn

Problem

You have some ruby code, a rake task for example, that outputs some results in the standard output, but you would like to test it in your unit tests.
MiniTest has capture_io and capture_subprocess_io, but there is nothing similar in UnitTest.

Solution

Looking at the code of the above MiniTest assertions you can create your own assertion to be used in your tests.

Create a new file under your test folder called MyAssertions and use the following code (taken from MiniTest), for your capture_output assertion:

Then include it in your test_helper.rb file with:

and use it in your tests like:

minitest assert_routing with method included in path

Email this to someoneShare on Google+Share on FacebookTweet about this on TwitterShare on LinkedIn

Problem

When trying to use the minitest assert_routing with the first parameter representing the path as a hash that includes both the path and the method, and run the tests rails complains about SyntaxErrors.

When trying to use it as suggested in the ‘Rails 4 Test Prescriptions’ Pragmatic Programmers book (p. 172 – Minitest and Routing) which is:

the error is:

even when trying to have the second parameter as a hash:

the error is similar:

Solution

Seems that you need to pass the parameters enclosed in brackets, so the following would work: