Using Shoulda to test login – should_require_login

by Justin Ball on October 2nd, 2008

I've had my problems with shoulda, but one very powerful component of the testing framework is the ability to create macros. Here's one that checks to make sure a user has to be logged in to access an action. Put it into test/shoulda_macros/authentication.rb. (You can name the file anything you want I just thought authentication.rb made sense)

 
Test::Unit::TestCase.class_eval do
  def self.should_require_login(*actions)
    actions.each do |action|
      should "Require login for '#{action}' action" do
        get(action)
        assert_redirected_to(login_url)
      end
    end
  end
end
</ruby>
 
Then inside your controller test do something like this:
<pre lang="ruby">
class UserControllerTest < ActionController::TestCase
  should_require_login :edit, :update, :destroy
end
 

  • http://www.alexjsharp.com Alex Sharp

    Nice! I was actually in the middle of writing a should_have_before_filters macro when I found this post. Very helpful.

  • http://rubenonrails.com Ruben

    Hi Justin, i think this macro don’t work fine under the hood because update and destroy don’t user the GET verb, i think that the parameter should be a hash with action and verb, what do you think?

    Regards.

  • http://www.justinball.com Justin Ball

    That is a good point. Those actions should require the appropriate ver – POST, PUT and DELETE. I don’t know that I want to pass a hash to the macro but perhaps that is the only correct way. I’m open to ideas and modifications if you have them.

  • http://rubenonrails.com Ruben

    Here is an idea: http://gist.github.com/45709

    Regards.

  • http://www.rubyinside.com/shoulda-roundup-elegant-maintainable-ruby-testing-1723.html Shoulda Roundup: Elegant, Maintainable Ruby Testing

    [...] Using Shoulda to test login – Justin Ball, has been looking into using Shoulda to test authentication. [...]

  • http://www.rubyinside.com.br/coletanea-de-artigos-sobre-o-shoulda-1375 Coletânea de artigos sobre o Shoulda

    [...] Usando o Shoulda para testar login – Justin Ball tem pesquisado a utilização do Shoulda para testar autenticação. [...]