While writing functional test cases, we might need a common utility to be used through our test cases.
These utility is generally recognized as "Macros" and more specifically as "Controller Macros".
With Rspec we can easily configure such Macros, as Rspec specifically provide a RSpec.configure block to define all our utility and support classes/modules used throughout our test suit. The RSpec.configure block looks like this.
RSpec.configure do config.extend(AuthenticateMacro) end
With Test::Unit which is a default testing tool provided by rials and its much more liter than Rspec, we can't use such configurations.
So I came up with my own method of defining Macros for Test::Unit
- Create a support file under test/support/ directory name it whatever you like.
- Define a module in that file and go ahead with the logic you would like to use in your controller test suits. The important step here is to include Devise::TestHelpers as I am using it for authenticating the users to log-In.
include Devise::TestHelpers module AuthenticateMacro def authenticate_me!(user=Factory(:user)) before do @current_user = user controller.stub!(:current_user).and_return(@current_user) session[:user_id] = @current_user.id end end end
- Next is to include the Macro in you test_helper.rb
class ActiveSupport::TestCase include AuthenticateMacro end
That's it now you can use your newly created macro(authenticate_me!) any where in the functional test suit to sign-In a user and test our controller actions. This will keep our test suit DRY and clean.