在我的一些控制器中,我有一个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
我缺少的东西?
如果你有一个不依赖于它们的应用程序,我真的鼓励你不要使用灯具进行测试。他们很难维持,真正令人沮丧。看看railscast,工厂没有灯具。 – nitecoder 2009-06-16 22:13:49
通过创建一个这样的用户,您不会测试您的控制器中是否调用了相应的检查程序(例如必须登录,必须是管理员等)。最好嘲笑预期的方法以确保它们被呼叫,例如对于摩卡:模拟(@controller).expects(:current_user).returns(@user) – 2011-07-28 16:12:59