Testing Rails 3 Generators With RSpec

written

Rails provides an easy way to test generators with test/unit, but what if you’re using RSpec?

One approach is to use aruba to generate a new Rails app, run bundle install, run your generator then verify it did the right thing. The problem with this approach is that it’s really, really slow. The approach Rails::Generators::TestCase takes is to run the generator in the current process against a temporary directory. This is much faster.

Today I released generator_spec for testing generators with RSpec. It’s a thin wrapper around Rails::Generators::TestCase, with the same assertions and setup methods available. It also comes with a really nice file structure matcher.

require "generator_spec/test_case"

describe InstallGenerator do
  include GeneratorSpec::TestCase
  destination File.expand_path("../../tmp", __FILE__)
  
  before do
    # Methods from Rails::Generators::TestCase are made available to the RSpec test
    prepare_destination
    run_generator
  end

  specify do
    destination_root.should have_structure {
      no_file "non_existant.rb"
      directory "config" do
        directory "initializers" do
          file "mygem.rb" do
            contains "# Change this"
          end
        end
      end
      directory "db" do
        directory "migrate" do
          migration "create_tests" do
            contains "class TestMigration"
          end
        end
      end
    }
  end
end