4

I have a Rails 3.2.3 application and I am using MiniTest and Capybara to run my integration tests. I rolled my own authentication and created a current_user helper_method in my application_controller.rb.

My application layout file only displays certain links, like logout, etc., when a user is logged in.

But the current_user method does not work during tests. It looks like this:

class ApplicationController < ActionController::Base
  protect_from_forgery
  private

  def authenticate
    if current_user.blank?
      redirect_to root_url, :alert => "You must first log in."
    end
  end

  def authenticate_admin
    unless current_user and current_user.admin?
      redirect_to root_url, :alert => "You must be logged in as an administrator to access     this feature."
    end
  end

  def current_user
    begin
      @current_user ||= User.find(session[:user_id]) if session[:user_id]
    rescue
      nil
    end
  end

  helper_method :current_user
end

So in my application.html.erb file there is:

<% unless current_user.blank? %>
 <li><%= link_to logout_path %></li>

So this works when I test it through the browser, but not in my test. "current_user" ends up being nil.

I am new to BDD, but is there something that prevents sessions from being created during tests? What am I missing?

RubyRedGrapefruit
  • 12,066
  • 16
  • 92
  • 193

1 Answers1

3

NOTE: helper methods defined in controllers are not included.

from here.

The solution is to organize them in a dedicated helper class.

forker
  • 2,609
  • 4
  • 23
  • 24
  • 3
    Thanks! I guess the same applies to MiniTest. But what about the session hash? Is that available or do I have to create one in my login helper? I'll give it a shot and report back. – RubyRedGrapefruit May 21 '12 at 11:45