我正在阅读railstutorial.org书,第9章。运行测试套件时,我无法摆脱以下故障。首先输入所有代码,然后通过复制和粘贴书籍来尝试所有代码。
...............F............................................
Failures:
1) SessionsController DELETE 'destroy' should sign a user out
Failure/Error: controller.should_not be_signed_in
expected signed_in? to return false, got true
# ./spec/controllers/sessions_controller_spec.rb:69:in `block (3 levels) in <top (required)>'
Finished in 8.28 seconds
60 examples, 1 failure
以下是sessions_controller_spec.rb中的测试代码:
describe "DELETE 'destroy'" do
it "should sign a user out" do
test_sign_in(Factory(:user))
delete :destroy
controller.should_not be_signed_in
response.should redirect_to(root_path)
end
end
(我认为)sessions_controller.rb的相关部分:
def destroy
sign_out
redirect_to root_path
end
sign_out方法可在sessions_helper.rb
中找到def current_user=(user)
@current_user ||= user_from_remember_token
end
def current_user
@current_user
end
def signed_in?
!current_user.nil?
end
def sign_out
cookies.delete(:remember_token)
self.current_user = nil
end
因此,如果我理解正确,那么在签入工厂用户之后,测试是调用SessionsController的destroy方法,该方法调用sign_out(来自SessionsHelper),该方法明确地将self.current_user设置为nil。然后测试检查signed_in?使用be_signed_in行。由于代码将self.current_user设置为nil,current_user.nil?应该返回true,!current_user.nil?应该返回false,这是测试想要的(controller.should_not be_signed_in)。
任何帮助将不胜感激。我正在同时学习Ruby,Rails和TDD,所以我不确定我的问题在哪里。
答案 0 :(得分:2)
问题是如何设置当前用户 - 您只是将其设置为从记忆令牌登录,您不会将其设置为nil。您可能想尝试以下操作:
def current_user=(user) @current_user = user end def current_user @current_user ||= user_from_remember_token end