[rspec-users] step definitons to check login

David Chelimsky dchelimsky at gmail.com
Tue Dec 16 14:54:53 EST 2008

On Tue, Dec 16, 2008 at 1:34 PM, James Byrne <lists at ruby-forum.com> wrote:
> I am working with the authlogic gem and trying to create a simple login
> test from cucumber features. The feature statement is:
> Given the user is not logged in
> The step definition for this is confounding me.  In the
> application_controller the authlogic tutorial recommends the following:
> private
>    def require_user
>      unless current_user
>        store_location
>        flash[:notice] = "You must sign in to access this page"
>        redirect_to new_user_session_url
>        return false
>      end
>    end
>    def require_no_user
>      if current_user
>        store_location
>        flash[:notice] = "You must be logged out to access this page"
>        redirect_to account_url
>        return false
>      end
> As these are private methods they are not directly accessible from the
> step definitions and I am at a loss as to how to proceed.  I could
> augment the application controller with a public user_authenticated
> method:
>  def user_authenticated
>     return true if current_user
>     false
>  end
> But it seems wrong to alter the application code for no other purpose
> than to ease testing.  Is there another approach that I should be using?

For things like session state, general consensus seems to be to go
through the app, not directly after its internals. So to log in I'd do
something like this:

Given /a user logged in as "(.*)"/ do |role|
  user = create_user(role, 'supersecret') #helper method
  visit login_path
  fill_in :username, :with => user.username
  fill_in :password, :with => 'supersecret'
  click_button "Login"

For an anonymous user, I usually just have an empty step:

Given /an anonymous user/ do; end

This assumes that you have to explicitly log in to be logged in, but
that seems like a safe assumption to me.

As for your point about changing code to make it testable, while I can
appreciate the desire to avoid modifying code for tests, if that's
what it takes to test it, I do it. In this case I wouldn't bother, but
as a general principle tests are part of the code base, just important
(if not more so) than the application code.


More information about the rspec-users mailing list