【问题标题】:How to test redirect when ActionController::InvalidAuthenticityTokenActionController::InvalidAuthenticityToken 时如何测试重定向
【发布时间】:2019-09-26 17:48:41
【问题描述】:

我的 ApplicationController 中有一个来自 ActionController::InvalidAuthenticityToken, with: :invalid_token 的rescue_from。

invalid_token 将用户重定向到漂亮的视图,并向最终用户提供更清晰的信息。

我试图在 Timecop gem 的帮助下编写一个模拟会话到期的测试,但我没有让它工作。

我已经尝试过这个解决方案来模拟一个过期的会话 a link

      user = create(:user, :with_company)

      visit new_user_session_path

      within "#sign_in_form" do
        fill_in :user_email, with: user.email
        fill_in :user_password, with: user.password

        click_button I18n.t("devise.sessions.new.sign_in")
      end

      assert page.has_link?(I18n.t("navbar.sign_out"))

      assert_current_path "/"

      # new_date = Time.zone.now + 1.month
      click_link I18n.t("breadcrumbs.orders")

      click_link I18n.t("orders.index.new_door")

      Timecop.travel 5.days.ago do  #session dosent get expired
        click_link I18n.t("pdf_button.title")
        assert_redirect_to "/invalid_token" #this brokes, it says it expects another path
      end
    end

我试图在我的测试中使用 Timecop gem 模拟过期会话以触发 InvalidAuthenticityToken,以便我可以看到我的重定向有效。

提前致谢!

【问题讨论】:

  • 您可以尝试更改网站上的身份验证令牌以使其无效(我认为您可以在水豚中执行自定义 javascript 以修改表单隐藏字段和标题元标记上的 auth_token)而不是使用 Timecop 移动当前日期时间。
  • 谢谢你,我会试试的,并就我的表现提供一些反馈

标签: ruby-on-rails capybara minitest


【解决方案1】:

您是否尝试过使用示例中使用的 from_now 时间?

类似这样的: Timecop.travel 5.days.from_now

【讨论】:

  • 也许会话没有受到影响,只有块内的代码,您可以尝试使用修改时间重新创建会话,甚至使用过期时间初始化它。
  • 如何重新创建测试中过期的会话?
  • 不幸的是,这确实有效,我最终在我的测试用例中模拟了异常,而不是使用 Timecop 或 reset_session
猜你喜欢
  • 2015-11-15
  • 2018-11-02
  • 2011-03-22
  • 2021-12-20
  • 2018-11-27
  • 2015-11-23
  • 2014-01-19
  • 1970-01-01
  • 2017-11-13
相关资源
最近更新 更多