Take me home

Asserting unauthenticated actions

Written by August Lilleaas, published November 28, 2007

Using assert_unauthenticated to test that your before_filter :require_login thingie works.

I’m not a part of the RSpec mob. It’s simply not appealing to me, good ol’ "test/unit" is my friend. And with these recent updates on the way fixtures works in 2.0, mocking is a bit less cool, too.

(I might be wrong about that mocking thought of mine, though, I’ve never mocked because I didn’t see the point of mocking, either. No mocking, no RSpec, what kind of person am I?)

So, I’m using "test/unit", and I wrote a method to assert that action x and y requires login.

def test_should_block_unauthenticated
  assert_unauthenticated :get => [:new, :edit], 
    :post =>  [:create, :update]
end

Here’s the implementation (in the test_helper.rb):

def assert_unauthenticated(requests = {})
  requests.each do |type, methods|
    methods.each do |method|
      perform_unauthenticated_assert(type, method)
    end
  end
end

def perform_unauthenticated_assert(type, method)
  # Call the method (e.g. perform the request)
  self.send(type, method)

  # Do the assert
  assert_block "Requesting #{method} with #{type} succeeded without login" do
    begin
      assert !@controller.current_user
      assert_redirected_to login_url
    rescue
      false
    end
  end
end

Change the assertions inside the assert_block call to whatever you need to assert.

And yes, please mail any suggestions on how to get rid of all the silly each-ing to augustlilleaas at google mail dot com.


Questions or comments?

Feel free to contact me on Twitter, @augustl, or e-mail me at august@augustl.com.