测试失败 - 在 redirect_to request.referrer 之后
Test failure - after redirect_to request.referrer
用户可以从多个位置提交表单以创建计划,随后应该返回到表单提交的原始位置。
我的调度控制器因此依赖于 request.referrer
。它在开发中按预期工作,看起来像这样:
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
我想 运行 一个 Rails 集成测试来测试这个。 request.referrer
然而在测试环境中似乎总是 nil,所以在 answer here 的帮助下,我通过在 Post 请求中包含一个 headers 散列来解决这个问题,就像这样:
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
此测试在 assert_not flash.empty?
失败
怎么回事,为什么flash被评估为空?
我注意到,如果在控制器中,我将 redirect_to request.referrer
更改为 redirect_to workouts_path
(或 workouts_url
),则测试通过。
感谢您的关注和帮助。
丹尼尔
我通过更改 headers 散列中的值广泛地解决了我自己的问题:
"http://example.com/workouts"
到 "http://www.example.com/workouts"
前者显示在 answer here 中,直接来自 Rails 指南,但是在 Rails 5 中工作,我发现“www”是必要的。
我在测试中用额外的一行深入了解了这一点:
assert_redirected_to workouts_url
在 the follow_redirect!
之前失败并确定了 url 差异。
丹尼尔
用户可以从多个位置提交表单以创建计划,随后应该返回到表单提交的原始位置。
我的调度控制器因此依赖于 request.referrer
。它在开发中按预期工作,看起来像这样:
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
我想 运行 一个 Rails 集成测试来测试这个。 request.referrer
然而在测试环境中似乎总是 nil,所以在 answer here 的帮助下,我通过在 Post 请求中包含一个 headers 散列来解决这个问题,就像这样:
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
此测试在 assert_not flash.empty?
失败
怎么回事,为什么flash被评估为空?
我注意到,如果在控制器中,我将 redirect_to request.referrer
更改为 redirect_to workouts_path
(或 workouts_url
),则测试通过。
感谢您的关注和帮助。
丹尼尔
我通过更改 headers 散列中的值广泛地解决了我自己的问题:
"http://example.com/workouts"
到 "http://www.example.com/workouts"
前者显示在 answer here 中,直接来自 Rails 指南,但是在 Rails 5 中工作,我发现“www”是必要的。
我在测试中用额外的一行深入了解了这一点:
assert_redirected_to workouts_url
在 the follow_redirect!
之前失败并确定了 url 差异。
丹尼尔