Sometimes you may need to create a set of rspec specifications with pretty similar structure and small differences. I’ve got such situation in my project and decided to try to use Ruby’s dynamic code generation features to make my spec file shorter.
I have some multiplexing helper in my templates which allows me to use the same template for different similar pages. This helper returns URL from the set of params and a type. It could accept 5 different url types and raises an Exception when requested URL type is invalid. Without this dynamic code generation feature I would need to create 5 different specifications (one for each URL type) to be able to see each URL type test as a separate line in test results log. But with this simple technique my code looks like following now:
describe VideoHelper, 'when profile_video_url method called'
do
before do
@user = mock('user')
…