03 12 / 2007
Share More Controller Specs with do_action
For most projects, our controllers tend to have some shared behavior that inherits from a base controller. Such as before filters for authentication or finding an AR model. RSpec also has a similar concept know as “shared behaviors”.
But it’s kind of difficult to do something like:
it 'should redirect to login if not logged in' do
do_post
response.should redirect_to(new_sessions_path)
end
because it might be a do_get, do_put, or do_delete.
do_action let’s you push common controller specs into a shared context without having to specify the exact action being called. add this to your spec_helper.rb
def do_action
%w(get post put delete render).each do |action|
self.send "do_#{action}" if self.respond_to?("do_#{action}")
end
end
And now you can put the previous code in a shared login spec
it 'should redirect to login if not logged in' do
do_action
response.should redirect_to(new_sessions_path)`
end