首页 > 解决方案 > 我很好奇什么时候应该使用 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

标签: ruby-on-railsruby-test

解决方案


突然在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

推荐阅读