You can either put the login_as in the setup method or have tests that capture the behavior of not being logged in separately from the behavior when the current user is already known. If you have some authorization process (what a user is allowed to do) separate from the authentication process (who is this user), then you may want to go that route since you have three conditions: not authenticated (i.e., not logged in); authenticated, but unauthorized (e.g., normal user accessing a privileged action); and authenticated and authorized. (Note that someone can be authorized to do something even when not authenticated such as signing up or seeing the login form.)
You can either put the login_as in the setup method or have tests that
capture the behavior of not being logged in separately from the
behavior when the current user is already known. If you have some
authorization process (what a user is allowed to do) separate from the
authentication process (who is this user), then you may want to go
that route since you have three conditions: not authenticated (i.e.,
not logged in); authenticated, but unauthorized (e.g., normal user
accessing a privileged action); and authenticated and authorized.
(Note that someone can be authorized to do something even when not
authenticated such as signing up or seeing the login form.)
Hi Rob -
Thanks for your help. I do have the authorization and authentication
processes separate from one another. I have:
def setup
login_as :quentin
end
But now the only way that I'm able to get this to work is if I include
this as the first line for all of my tests.
assert login_as("quentin")
If that assert line is missing, then my response changes from (:success)
to (302) - redirect.
It's also possible that you have two definitions for setup and only the last one is really having any effect (since its definition would have overwritten the original one).
You ought to have a bit more in your setup than that for a functional
test.
The tests are actually testing other controller functions, not the login
function. But I do have login tests. Is it possible to have the def
setup with the login_as :admin and also have tests that test the login.
For example I would want Test 1 - tests the login, Test 2 - tests the
controller function that needs the login.
If I have def setup with the login, will Test 1 then be useless or can I
set the login user to nil or something like that?
The definition of login_as is in:
lib/authenticated_test_helper.rb
You get the effect of logging out with:
login_as nil
It can be immensely helpful to read the Ruby code that implements this kind of thing. One reason is to see the answer to this kind of question directly, but also you start to see how easy some of the "magic" really is and start to craft some of your own.