Puppet: System Administration Automated

Using test/unit-style setup/teardown in RSpec


I've been starting to use RSpec within Puppet recently, and one of the things that really annoys me about RSpec is that it uses hooks for setup and teardown instead of methods:

describe "My stuff" do
    before do
        ...
    end

    it "should ... "

    after do
        ...
    end
end

Sure, it's just as functional in the simple cases, but the simple cases don't go very far when you've got 50k lines of test code. Specifically, this makes it stupidly difficult to have modules that include modules, all of which have their own setup and teardown.

However, after reading through the RSpec code today, I found a workaround. You can provide hooks in the RSpec configuration that add new before and after hooks for all of your tests:

Spec::Runner.configure do |config|
  config.mock_with :mocha
  config.prepend_before :each do
      setup() if respond_to? :setup
  end

  config.prepend_after :each do
      teardown() if respond_to? :teardown
  end
end

Now I have test/unit-style setup and teardown, which, importantly, means I can easily use my existing test modules (since I'm in the process of converting my tests from test/unit to RSpec), and it also means that those modules can include other modules, or a given behaviour can include multiple modules, and all of the modules' hooks will get called.

Whew!

add to del.icio.us Add to Blinkslist add to furl Digg it add to ma.gnolia Stumble It! add to simpy seed the vine TailRank post to facebook

Tue, 11 Sep 2007 | Tags: , , ,