Tuesday, September 05, 2006

Ruby/Rails Unit Testing in less than 1 second

I previously wrote about removing the database dependency from Ruby on Rails Unit Tests. I'm pleased to say that several months later my team continues to write unit tests that do not require database access. As a result, our unit tests run quite quickly:
Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.7.1/lib/rake/rake_test_loader
Started
....................................................................................................................................
Finished in 0.555897 seconds.

132 tests, 219 assertions, 0 failures, 0 errors
However, there is another factor that contributes to our test time: Stubba and Mocha. Stubba and Mocha have become tools that I would not want to live without.

Mocha is my new favorite mocking framework. Mocha's syntax is intuative and the mocks are auto-verified.
def test_execute(command='sql string', connection=mock)
connection.expects(:execute).with(command)
SqlExecutor.execute(command, connection)
end
Stubba is similar to Mocha except it adds mock and stub capabilities to concrete classes.
def test_execute(command='sql string')
DatabaseConnection.expects(:execute).with(command)
SqlExecutor.execute(command)
end
Stubba can also be used for easy white box unit testing of specific methods. Stubba allows you to mock some methods of a concrete class while testing the actual implementations of the other methods.
def test_parse(text='any text')
Parser.expects(:preprocess).returns('condition.add')
Builder.expects(:build)
Parser.parse(text)
end
Both Stubba and Mocha allow our tests to be concise and descriptive while increasing test performance.

For more information on removing the database dependency check out this entry and for more info on Stubba and Mocha check out the RubyForge page.
Post a Comment