jas*_*328 3 ruby rspec ruby-on-rails ruby-on-rails-4
我有一个 rspec 测试来测试控制器操作。
class SalesController < ApplicationController
def create
# This redirect sends the user to SalesController#go_to_home
redirect_to '/go_to_home'
end
def go_to_home
redirect_to '/'
end
end
Run Code Online (Sandbox Code Playgroud)
我的控制器测试看起来像
RSpec.describe SalesController, type: :controller do
include PathsHelper
describe 'POST create' do
post :create
expect(response).to redirect_to '/'
end
end
Run Code Online (Sandbox Code Playgroud)
然而,当我运行测试时,它告诉我:
Expected response to be a redirect to <http://test.host/> but was a redirect to <http://test.host/go_to_home>.
Expected "http://test.host/" to be === "http://test.host/go_to_home".
Run Code Online (Sandbox Code Playgroud)
/go_to_home将把用户发送到 SalesController#go_to_home。如何测试响应最终是否会引导至带有 url 的主页http://test.host/?
为什么您期望在规范中重定向到“/”?从您粘贴的控制器代码中,点击创建操作后,您将被重定向到“/go_to_home”
尝试将规格更改为:
expect(response).to redirect_to '/go_to_home'
Run Code Online (Sandbox Code Playgroud)
编辑:
这是一个真实的例子还是代码只是为了分享您想要实现的目标?我认为 rspec 在转到“/go_to_home”后不会遵循重定向,我认为很好。
如果您正在测试创建操作,则可以测试重定向到“/go_to_home”,因为这就是操作正在执行的操作。然后,您可以对其他操作进行另一个测试go_to_home,并期望重定向到 root。
您是否从其他地方调用“go_to_home”操作?