Running Tests Against a Gem

2008.05.30 06:00

I use Hoe to build my projects. Sometimes I add a new source file and forget to update my Manifest.txt, so my gem doesn’t contain all of the necessary files. My tests pass, but then I install my gem and it doesn’t work, usually due to a failed require.

So I thought: it would be nice if I could run my tests against the gem, so I could know that it was built correctly.

Here’s how I do it:

def recreate_dir(dir)
  FileUtils.rm_r(dir) if File.exist?(dir)
  FileUtils.mkdir_p(dir)
end

def error(msg)
  $stderr.puts "ERROR -- #{msg}"
  exit 1
end

def run(command)
  puts command
  error 'command failed' unless system(command)
end

namespace :my do

  # initializes test output dir
  task :setup do
    # typical setup stuff
  end

  Spec::Rake::SpecTask.new(:run_system_specs) do |t|
    # typical RSpec stuff
  end

  desc "Runs RSpec System Tests against gem"
  task :system_specs_gem => ['my:setup'] do
    # builds gem
    Rake::Task[:gem].invoke

    # my code prettifier doesn't like this line.
    # uncomment if you want this code to actually work.
    #gem = Dir.glob("pkg/*.gem").first

    # installs gem into tmp dir
    install_dir = 'tmp'
    recreate_dir(install_dir)
    run "gem install --install-dir=#{install_dir} --no-rdoc --no-ri -y #{gem}"

    # points tests to gem and runs
    ENV['GEM_PATH'] = install_dir
    Rake::Task['my:run_system_specs'].invoke
  end

end

Notes:

  • Hoe gives me the :gem task for free
  • I put my tasks in the :my namespace so I can easily differentiate them from the ones provided by Hoe
  • I don’t run my tests in this fashion as I’m writing code, but I try to do it before I commit. My automated build runs the tests against the gem before it installs it on my local system.

Comments? (moderated as hell)

allowed HTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>