Shoulda macros allows you to embrace your inner slacker
So I think I’ve discovered Shoulda’s secret sauce, the reason why you should use it.
It’s nice and all to have a decent syntax for doing nested contexts, and declaring tests. But the real power comes from having macros that define tests for you.
Here’s a fully shoulda-ified model test (from an example on the Shoulda website):
Imagine how much more code you’d have if you were to do this by hand.
It’s not magic though. It’s pretty easy to write your own. To start with, you can just define them in your
Here’s the jist of what you do:
- Define a class method, usually like
should_something_something, or maybe
- In this method, declare a
shouldblock. You’d probably want to name this dynamically based on the parameters given to your method.
- Assert stuff.
As an example, here’s something I wrote recently:
Then in your tests, you can use it like:
It’s pretty straightforward stuff.
If you start to get a lot of these in your
test_helper.rb, you can always move them into module, include/extend them. If they are general enough, who knows, maybe release it as a gem.