加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在Rails 5中使用Rspec测试redirect_back

发布时间:2020-12-17 02:56:31 所属栏目:百科 来源:网络整理
导读:我正在升级我的Rails 5应用程序,目前正在克服以下弃用: DEPRECATION WARNING: `redirect_to :back` is deprecated and will be removed from Rails 5.1. Please use `redirect_back(fallback_location: fallback_location)` where `fallback_location` repr
我正在升级我的Rails 5应用程序,目前正在克服以下弃用:

DEPRECATION WARNING: `redirect_to :back` is deprecated and will be removed from Rails 5.1. Please use `redirect_back(fallback_location: fallback_location)` where `fallback_location` represents the location to use if the request has no HTTP referer information. (called from block (3 levels) in <top (required)> at /path/to/some/controller_spec.rb:74)

别担心.刚刚将控制器切换到新格式:

redirect_back(fallback_location: home_path,message: "Some error")

但是,警告并没有消失,因为测试仍然看着:回来,像这样:

expect(response).to redirect_to(:back)

我没有看到任何克服这种弃用的首选方法.有没有其他方法来测试这个,而无需在我的测试中手动指定HTTP_REFERER?

解决方法

好吧,我看了一下rails / rspec-rails的来源,看起来很凄凉.这是新的重定向代码:

def redirect_back(fallback_location:,**args)
  if referer = request.headers["Referer"]
    redirect_to referer,**args
  else
    redirect_to fallback_location,**args
  end
end

并且rspec-rails专门测试重定向位置,如下所示:

@scope.assert_redirected_to(@expected)

这意味着如果我们不知道重定向位置(或至少是后备位置),我们几乎不走运. rspec匹配器本身只是测试响应对象是否响应重定向?使用true,但由于Rails重定向当前不会跟踪它们是来自redirect_to还是redirect_back,因此没有区别的情况.

目前看来,给定以下重定向:

redirect_back(fallback_location: "/foo/bar")

我们可以管理的最佳控制器测试是测试:

expect(response).to redirect_to("/foo/bar")

如果我们设法在某个时刻提供Referer标头,那将会失败.

更多更新!我询问了rspec-rails,他们对支持这方面的更新不感兴趣.这是一个合理的立场,因为我真的只是在寻找干净的语法来做断言.相反,我已经改为:

let(:back) { 'http://google.com' }
before { request.env['HTTP_REFERER'] = back }

现在我可以保留以下格式:

expect(response).to redirect_to(back)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读