Rails special sauce: Test::Unit setup and teardown
Rails adds plenty of special sauce to Ruby standard library.
Being a fan of testing and all that, let me show you what I found while spelunking around the Rails supporting test cases:
What the?!?! I thought you had to
def setup for setup methods…. but here, it’s a method call, that takes a symbol.
This reminds me of something…
Shocking to say, but they are similar, because they both use ActiveSupport::Callbacks. Basically, this allows us to specify setup and teardown blocks the same way we’ve been specifying ActionController filters and ActiveRecord callbacks:
- Using a method name as a symbol
- Using a block
- Using a method
- Using conditions
- Determined by a lambda
- Determined by a method name as a symbol
Let’s try using these all together:
Loaded suite test-test Started called by using symbol of a method name called from a setup block called from def setup I am testing nothing . Finished in 0.000371 seconds. 1 tests, 1 assertions, 0 failures, 0 errors
So why is this significant?
- Isolate related setup into their own methods
teardownbe conditionally done
- Allows superclasses to give default
teardown, while allowing subclasses to have their own, without needing to call