功能测试Authlogic?

时间:2009-06-16 01:04:24

标签: ruby-on-rails ruby tdd

在我的一些控制器中,我有一个before_filter来检查用户是否已登录?对于CRUD行动。

application.rb中

def logged_in?
  unless current_user
    redirect_to root_path
  end
end

private
def current_user_session
  return @current_user_session if defined?(@current_user_session)
  @current_user_session = UserSession.find
end

def current_user
  return @current_user if defined?(@current_user)
  @current_user = current_user_session && current_user_session.record
end

但是现在我的功能测试失败了,因为它重定向到root。所以我需要一种方法来模拟会话已经创建,但我尝试过的任何东西都没有。这是我现在所拥有的,测试几乎忽略了它:

test_helper.rb中

class ActionController::TestCase
  setup :activate_authlogic
end

posts_controller_test.rb

class PostsControllerTest < ActionController::TestCase
  setup do
    UserSession.create(:username => "dmix", :password => "12345")
  end

  test "should get new" do  
    get :new
    assert_response :success
  end

我错过了什么吗?

5 个答案:

答案 0 :(得分:5)

您应该在UserSession.create中传递ActiveRecord对象

类似的东西:

u = users(:dmix)
UserSession.create(u)

答案 1 :(得分:4)

http://rdoc.info/github/binarylogic/authlogic/master/Authlogic/TestCase

首先,您需要激活AuthLogic,以便在测试中使用它。

setup :activate_authlogic

然后你需要一个有效的用户记录,正如Anton Mironov指出的那样。

答案 2 :(得分:3)

我在我的控制器的rspec测试中所做的就是创建一个带有机械师的用户,然后将该用户指定为current_user。

def login_user(options = {})
  user = User.make(options)
  @controller.stub!(:current_user).and_return(user)
end

这会将current_user附加到控制器,这意味着你的logged_in?方法适用于你的测试。

你显然可能需要调整它在Test :: Unit中工作,如果不使用它就没有Machinist,因为我使用rspec,但我确信原理是一样的。

答案 3 :(得分:1)

如果您希望所有测试都设置为Authlogic:

,请将其放在test_helper.rb
class ActionController::TestCase
  def self.inherited(subclass)
    subclass.instance_eval do
      setup :activate_authlogic
    end
  end
end

答案 4 :(得分:0)

Here是AuthLogic测试文档的链接。这是一个重要的,但有点埋没(同样的链接Simone发布,但他的不再工作)。

该页面包含使用AuthLogic进行身份验证测试应用程序所需的所有信息。

此外,正如railsninja建议的那样,使用工厂而不是固定装置。看看factory_girlmachinist;选择你的毒药,它们都很好。