Metaprogramming Unit Tests
by Sean Cribbs
Here's how a lot of my tests look right after I've created my
model. I got this pattern from Rick
restful_authentication generator plugin.
It's a nice clear pattern, but I inevitably make typing errors, especially in the creation method. This problem is exacerbated when I'm writing essentially the same test for tons of different models. Here's how I'd love it to look:
All that's needed now is a little reflection
define_method magic. Here's what I coded into
test_helper.rb (inside the Test::Unit::TestCase
class), with some help from
What I love about this is that it is both a prime example for extraction into a pattern, and that it serves my desire to be a lazy programmer! Kudos again for Ruby. I also added in another method for testing creation validations, which I'll let you investigate in this pastie.