我是rails的新手,从设置我的第一个测试套件开始。
在我的测试中,我一直遇到以下失败:
Expected response to be a <redirect>, but was <200>
这种反应很奇怪,因为在使用浏览器进行测试时,重定向显然有效。有没有人知道这里可能会发生什么,或者诊断此类问题的最佳方法是什么。例如,有没有办法找出200消息的页面。
测试脚本(user_controller_test.rb)
test "when correct should redirect to dashboard" do
log_in_as(@user_one)
assert_redirected_to dashboard_url
end
完整的控制台消息
FAIL["test_should_get_dashboard_when_correct_user", UsersControllerTest, 2015-12-23 18:06:20 +1100]
test_should_get_dashboard_when_correct_user#UsersControllerTest (1450854380.57s)
Expected response to be a <redirect>, but was <200>
test/controllers/users_controller_test.rb:27:in `block in <class:UsersControllerTest>'
控制器:
class SessionsController < ApplicationController
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in user
params[:session][:remember_me] == '1' ? remember(user) : forget(user)
redirect_back_or dashboard
else
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
end
答案 0 :(得分:2)
您的测试有误。
这就是控制器中的代码所说的内容:
if user && user.authenticate(params[:session][:password])
redirect_back_or dashboard
else
render 'new'
end
# if user is not nil AND user can authenticate with given params
# success (redirect)
# else the params passed to the controller did not authenticate the user
# fail (render 200)
然后你的测试说:
log_in_as(@user_one)
assert_redirected_to dashboard_url
# login user manually, rather than assign params
# check if the controller action redirected, meaning check if it could authenticate with the given params that you did not assign
看到问题?如果希望它传递if
语句,则需要设置控制器操作正在检查的参数。