How to test code that behaves conditionally based on gem existence?

Working on bundler-bouncer | RubyGems.org | your community gem host, the problem is it
uses
ANSI escape sequences to colour the output, which doesn’t work on
Windows.
I’ve seen some gems that will use term-ansicolor to colour the output,
if it
is present, and otherwise won’t use it. That seemed easier than trying
to
detect whether we were on Windows or not, but I still can’t figure out
how
to test something like that. Everything I’ve thought of has gotten
really
ugly really quick. Any suggestions?

Because I don’t understand anything in your post, I’ll answer the
question posed in your title:

begin
require ‘non_existent’
puts “Gem exists if this prints”
rescue LoadError
puts “Gem doesn’t exist. :(”
end

Whoops. How to test code like that??

How about something like this:

def load_em_up(gems, debug=false)
results = gems.map do |gem|
begin
require gem

  if debug
    return 'loaded'
  end

  puts "Gem '#{gem}' exists."
  #path1()
rescue LoadError
  if debug
    return 'load error'
  end

  puts "Gem '#{gem}' doesn't exist. :("
  #path2()
end

end
end

#load_em_up([‘date’, ‘non-existent’])

require ‘test/unit’

class TestGemLoading < Test::Unit::TestCase
def test_gem_should_load
assert_equal(‘loaded’, load_em_up([‘date’]), true )
end

def test_gem_should_not_load
assert_equal(‘load error’, load_em_up([‘non-existent’]), true )
end
end

re: ANSI color sequences in Windows cmd.exe try:

http://adoxa.110mb.com/ansicon/

quickstart:

  • put on PATH
  • type ansicon -p
  • see if it works with bundler-bouncer

On Mon, Jun 27, 2011 at 20:22, Josh C. [email protected] wrote:

Working on bundler-bouncer | RubyGems.org | your community gem host, the problem is it uses
ANSI escape sequences to colour the output, which doesn’t work on Windows.
I’ve seen some gems that will use term-ansicolor to colour the output, if it
is present, and otherwise won’t use it. That seemed easier than trying to
detect whether we were on Windows or not, but I still can’t figure out how
to test something like that. Everything I’ve thought of has gotten really
ugly really quick. Any suggestions?

I usually make sure the test for “use ANSI colour” is in a separate
function. That can test for the presence of the gem, and anything
else you want it to do. It also, conveniently, makes it easy to stub
out that individual function to make tests run as if it wasn’t
present.

I would use it to either define different output functions, or embed
it inside the same output functions, rather than having it visible
elsewhere in the code. Hide the colour part in your output
abstraction.

Daniel