2009-06-16 175 views
5

在我的一些控制器中,我有一个before_filter用来检查用户是否登录?为CRUD行动。功能测试Authlogic?

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 

但现在我的功能测试失败,因为它重定向到根。所以我需要一种方法来模拟一个会话已经创建,但没有我试过的工作。下面有什么,我现在所拥有的,并测试几乎忽略它:

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

你应该通过ActiveRecord的对象UserSession.create

喜欢的东西:

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

如果你有一个不依赖于它们的应用程序,我真的鼓励你不要使用灯具进行测试。他们很难维持,真正令人沮丧。看看railscast,工厂没有灯具。 – nitecoder 2009-06-16 22:13:49

+0

通过创建一个这样的用户,您不会测试您的控制器中是否调用了相应的检查程序(例如必须登录,必须是管理员等)。最好嘲笑预期的方法以确保它们被呼叫,例如对于摩卡:模拟(@controller).expects(:current_user).returns(@user) – 2011-07-28 16:12:59

3

我在我的控制器的rspec测试中做的所有事情是创建一个User with Machinist,然后将该用户分配给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,但我确定原理是一样的。

4

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

首先,你需要激活AuthLogic,让您可以在您的测试中使用它。

setup :activate_authlogic 

然后,您需要一个有效的用户记录,如Anton Mironov指出的那样。如果你希望所有的测试设置Authlogic

+0

链接到文档是死的,试试这里:http://rdoc.info/github/binarylogic/authlogic/master/Authlogic/ TestCase – 2011-07-03 20:32:51

1

把这个test_helper.rb

class ActionController::TestCase 
    def self.inherited(subclass) 
    subclass.instance_eval do 
     setup :activate_authlogic 
    end 
    end 
end 
0

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

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

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