【问题标题】:I am curious about the machanism about when should I use follow_rediret! and when shouldn't?我很好奇什么时候应该使用 follow_rediret 的机制!什么时候不应该?
【发布时间】:2021-05-10 05:11:14
【问题描述】:

我正在阅读关于如何使用表单测试提交的第7章,下面有两个测试用例,令人困惑的部分是关于我应该何时使用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-rails ruby-test


    【解决方案1】:

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

    【讨论】:

    • 是的,就是这样 ^.^ 很好,自己找到它,
    • @Geoffroy 谢谢你的话证实了我的假设。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    • 2021-09-07
    • 2019-12-26
    • 2013-10-31
    • 2010-12-30
    • 1970-01-01
    相关资源
    最近更新 更多