ruby-on-rails - 我很好奇什么时候应该使用 follow_rediret 的机制!什么时候不应该?
问题描述
我正在阅读关于如何使用表单测试提交的第 7 章,书籍 <The ruby on rails tutorial 6th 2021>,下面有两个测试用例,令人困惑的部分是关于何时应该使用 follow_redirect!为什么第一种情况不需要这条线,而第二种需要呢?我的假设是关于 URL 本身,因为在第一种情况下,URL 一直是“用户/新”,但第二个后来变成“用户/显示”(在成功注册新用户后)。
非常感谢你的帮助。
require 'test_helper'
class UsersSignupTest < ActionDispatch::IntegrationTest
test 'invalid signup information' do
get signup_path
assert_no_difference 'User.count' do
post users_path, params: { user: { name: '',
email: 'user@invalid',
password: 'foo',
password_confirmation: 'bar' } }
end
assert_template 'users/new'
assert_select 'div#error_explanation'
assert_select 'div.alert.alert-danger'
end
test 'valid signup information' do
get signup_path
assert_difference 'User.count', 1 do
post users_path, params: { user: { name: 'Example User',
email: 'user@example.com',
password: 'password',
password_confirmation: 'password' } }
end
follow_redirect! #It's all about This line!
assert_template 'users/show'
end
end
解决方案
突然在users_controller.rb文件中找到这部分代码,我猜可能是这个原因,因为提交不成功时,我只是渲染'新'页面,但提交成功时,我重定向_到@user!
真的希望有人能给出任何确认,非常感谢。
def create
@user = User.new(user_params)
if @user.save
puts users_url
# puts root_url
puts user_url(@user)
flash[:success] = 'Welcome to the Sample App!'
redirect_to @user
# redirect_to root_path
else
render 'new'
end
end
推荐阅读
- javascript - 在响应式 react-sidebar 包中使用 onClick() 函数不起作用
- c# - C# foreach 列表元素在列表中添加一个 AddField
- java - 带分隔坐标的交互式图像
- android - 从不同的类向应用程序发送值但需要单击(点击)两次按钮 - Flutter / Dart
- python - 重新排列 2 个不同长度的数组以创建第三个数组 Numpy Python
- c - 数组初始值设定项必须是初始值设定项列表或字符串字面量错误
- reactjs - 如何使用反应钩子添加级联下拉菜单?
- testing - 如何计算以下问题的服务器停机时间和可用性?
- c# - 如何从两个表达式创建有效的 lambda 谓词?
- c# - C#在另一种方法中使用变量