Fri 11 May 2007
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:
before do
@user = mock('user')
end
url_types = {
'personal_feed' => 'personal_feed',
'favorites' => 'favorites',
'voted' => 'voted_videos',
'posted' => 'posted_videos',
'commented' => 'commented_videos'
}
url_types.each do |url_type, route|
it "should return #{route}_url for #{url_type} type urls" do
@user.should_receive(:login).at_least(1).times.and_return('login')
profile_video_url(url_type, @user, 2, 'expert').should == send("#{route}_url", @user, 2, 'expert')
end
end
it 'should raise ArgumentError("Invalid feed type") on invalid url_types' do
lambda { profile_video_url('crap', @user, 2, 'expert') }.should raise_error(ArgumentError, 'Invalid feed type')
end
end
This technique could be used even to create entire describe sections, but I would not like to show tons of code here. Anyways, the idea is pretty simple: you could use some loop with nested describe section and send() method calls to dynamically construct your code.
- Using Nginx, SSI and Memcache to Make Your Web Applications Faster
- Using X-Accel-Redirect Header With Nginx to Implement Controlled Downloads (with rails and php examples)
- Typical Configurations Overview For Nginx HTTP(S) Reverse Proxy/Web Server
- List of Great Online Tools, Generators, Checkers
- Advanced Squid Caching for Rails Applications: Preface

Add New Comment
Thanks. Your comment is awaiting approval by a moderator.
Do you already have an account? Log in and claim this comment.
Add New Comment
Trackbacks
(Trackback URL)