Rspec 测试redirect_to :back
如何在 rspec 中测试 redirect_to :back
?
我明白了
ActionController::RedirectBackError
:
此操作的请求中未设置HTTP_REFERER
,因此无法成功调用redirect_to :back
。如果这是测试,请确保指定request.env["HTTP_REFERER"]
。
如何在测试中设置 HTTP_REFERER
?
How do you test redirect_to :back
in rspec?
I get
ActionController::RedirectBackError
:
NoHTTP_REFERER
was set in the request to this action, soredirect_to :back
could not be called successfully. If this is a test, make sure to specifyrequest.env["HTTP_REFERER"]
.
How do I go about setting the HTTP_REFERER
in my test?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用 RSpec,您可以在
before
块中设置引用者。当我尝试在测试中直接设置引用者时,无论我把它放在哪里似乎都不起作用,但是 before 块可以解决问题。Using RSpec, you can set the referer in a
before
block. When I tried to set the referer directly in the test, it didn't seem to work no matter where I put it, but the before block does the trick.如果有人偶然发现这一点并且他们正在使用
request
规范,则您需要在您发出的请求上显式设置标头。测试请求的格式取决于您使用的 RSpec 版本以及是否可以使用关键字参数而不是位置参数。https://relishapp.com/rspec/rspec-rails/docs /请求规范/请求规范
If someone stumbles upon this and they're using
request
specs, you'll need to explicitly set the headers on the request you're making. The format of the test request depends on which version of RSpec you're using and if you can use keyword arguments instead of positional arguments.https://relishapp.com/rspec/rspec-rails/docs/request-specs/request-spec
来自 rails 指南 当使用新的请求样式请求请求时:
From the rails guide when requesting the request with the new request style:
恕我直言,接受的答案有点hacky。更好的替代方案是将
HTTP_REFERER
设置为应用程序中的实际 url,然后期望重定向回来:对于较新版本的 rspec,您可以使用期望来代替:
IMHO the accepted answer is a bit hacky. A better alternative would be to set the
HTTP_REFERER
to an actual url in your application and then expect to be redirected back:For newer versions of rspec, you can use expectations instead:
关于在集成测试中测试 :back 链接,我首先访问一个死端页面,我认为该页面不太可能被用作链接,然后访问我正在测试的页面。所以我的代码看起来像这样
但是这确实有一个缺陷,如果链接确实是到 deadend_path,那么测试将错误地通过。
In regard to testing :back links in integration tests, I first visit a deadend page, that I think is not likely to be ever used as a link, and then the page I am testing. So my code looks like this
However this does have the flaw that if the link is really to the deadend_path, then the test will incorrectly pass.