RSpec redirect_to和return与redirect_to && return

non*_*ame 5 ruby rspec ruby-on-rails rspec-rails

我有一个在某些情况下在某些点重定向的控制器。当我将参数传递给控制器​​规范中的规范帮助器方法(使用最新的RSpec)以触发这些条件时,

ActionView::MissingTemplate
Run Code Online (Sandbox Code Playgroud)

错误。在仔细检查时,我应该重定向,如下所示:

redirect_to root_path && return
Run Code Online (Sandbox Code Playgroud)

然后在我的测试套件中引发了异常。我在应该被调用的控制器的索引函数中设置了一个断点(我重定向到的路由所指向的断点),并且在我的测试套件中从未调用过该断点。当我在开发环境和生产环境中运行该代码时,它似乎可以正常工作,但对于此测试,它不会让步。有任何想法吗?

我的测试看起来像这样:

describe TestController do
  it 'redirects properly with failure' do
    get :create, provider: 'test', error: 'access_denied'
    expect(response.body).to match 'test'
  end
end
Run Code Online (Sandbox Code Playgroud)

编辑:

更新!

似乎将我的重定向更改为

redirect_to root_path and return
Run Code Online (Sandbox Code Playgroud)

在RSpec中工作。

我不知道为什么&&运算符的优先级会违反规范。有人对这里发生的事情有任何解释吗?

hen*_*tha 7

根据Rails指南

确保使用and return而不是,&& return因为&& returnRuby语言中的运算符优先级将使其无法使用。

如果您喜欢使用&&,请将参数括render在括号中:

redirect_to(root_path) && return
Run Code Online (Sandbox Code Playgroud)


Fre*_*ung 5

所不同的&&具有更高的优先级and。高优先级导致 ruby​​ 将其解析为

redirect_to(root_path && return)
Run Code Online (Sandbox Code Playgroud)

方法当然必须在方法本身被调用之前评估它们的参数,所以在这种情况下redirect_to永远不会被调用,因为 ruby​​ 命中第return一个。

另一方面,较低的优先级and意味着它被解析为

(redirect_to root_path) and return
Run Code Online (Sandbox Code Playgroud)

这就是您想要的 - 首先进行重定向然后返回。