简体   繁体   English

测试失败 - 在 redirect_to request.referrer 之后

[英]Test failure - after redirect_to request.referrer

A User can submit a form to create a Scheduling from more than one place and should subsequently be returned to the original place of form submission.用户可以从多个位置提交表单以创建调度,随后应返回到表单提交的原始位置。

My Schedulings Controller, therefore relies on request.referrer .因此,我的调度控制器依赖于request.referrer It works as intended in development and looks something like this:它在开发中按预期工作,看起来像这样:

class SchedulingsController < ApplicationController
#stuff not relevant to the question removed
  def create
    @scheduling = current_user.schedulings.build(scheduling_params)
     if @scheduling.save
       redirect_to request.referrer
       flash[:success] = "scheduled!"
     else
     # do something not relevant to the question
     end
   end
end

I wish to run a Rails integration test to test this.我希望运行 Rails 集成测试来测试它。 request.referrer however appears to always be nil in the Test environment, so with help from an answer here I have worked around this by including a headers hash in the Post request like this:然而request.referrer在测试环境中似乎始终为零,因此在此处答案的帮助下,我通过在 Post 请求中包含标题哈希来解决此问题,如下所示:

class SchedulingsCreateTest < ActionDispatch::IntegrationTest
 
  test "valid input for new scheduling" do
    assert_difference 'Scheduling.count', 1 do
      post schedulings_path, params: { scheduling: { start_time: Time.now },
                                       headers: { "HTTP_REFERER" => "http://example.com/workouts" }
    end

    follow_redirect!
    assert_template 'workouts/index'
    assert_not flash.empty?
  end

This test fails at assert_not flash.empty?此测试在assert_not flash.empty?处失败assert_not flash.empty? What is happening, why is the flash assessed as empty?发生了什么,为什么闪存被评估为空?

I note that if, in the controller, I change redirect_to request.referrer to redirect_to workouts_path (or workouts_url ), the test passes.我注意到,如果在控制器中,我将redirect_to request.referrer更改为redirect_to workouts_path (或workouts_url ),则测试通过。

Thanks for your interest and any help.感谢您的关注和任何帮助。

Daniel丹尼尔

I have broadly solved my own question by changing the value in the headers hash from:我通过更改标题哈希中的值从以下位置广泛解决了我自己的问题:

"http://example.com/workouts" to "http://www.example.com/workouts" "http://example.com/workouts""http://www.example.com/workouts"

the former is shown in an answer here and is sourced directly from the Rails Guide, however working in Rails 5, I found the “www” is necessary.前者显示在此处答案中,并且直接来自 Rails 指南,但是在 Rails 5 中工作时,我发现“www”是必要的。

I got to the bottom of this with an extra line in my test:我在测试中用额外的一行深入了解了这一点:

assert_redirected_to workouts_url before the follow_redirect! assert_redirected_to workouts_url之前the follow_redirect! , which failed and identified the url discrepancy. ,失败并确定了 url 差异。

Daniel丹尼尔

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM