Showing posts with label testing. Show all posts
Showing posts with label testing. Show all posts

Tuesday, 8 September 2009

Capturing stdout for tests in Ruby

I found this on Thinking Digitally that allows me to capture stdout and test that it is correct.
require 'stringio'

def capture_stdout
out = StringIO.new
$stdout = out
yield
return out
ensure
$stdout = STDOUT
end

Which can be used as follows
class ATest < Test::Unit::TestCase
def zxc(text, count)
count.times {puts text.upcase}
end

def test_stdout_capture
out = capture_stdout do
zxc('yes', 3)
end

assert_equal "YES\nYES\nYES\n", out.string
end
end

Tuesday, 16 June 2009

Looking good, feeling bad

What do you feel about the following line of output?

20 tests, 20 assertions, 0 failures, 0 errors

Happy, sad or nervous?

Well Ruby helpfully generates the scaffolding for tests whenever you create a new controller. They look like this:

require 'test_helper'

class HomeControllerTest < ActionController::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end

So I have just tested that true does really equal true, twenty times. That warm fuzzy feeling is changing into a nervous tick. I propose a new rule, tests should actually test something or delete them.