gpt4 book ai didi

ruby-on-rails - 在 RSpec 中测试 Controller 的重定向

转载 作者:数据小太阳 更新时间:2023-10-29 08:43:31 25 4
gpt4 key购买 nike

我有一个 rspec 测试来测试 Controller 操作。

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

我的 Controller 测试看起来像

RSpec.describe SalesController, type: :controller do
include PathsHelper

describe 'POST create' do
post :create

expect(response).to redirect_to '/'
end
end

但是,当我运行测试时,它告诉我:

   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".

/go_to_home 会将用户发送到 SalesController#go_to_home。我如何测试响应最终是否会指向带有 url http://test.host/ 的主页?

最佳答案

为什么您希望在规范中重定向到“/”?从您粘贴的 Controller 代码中,您将在点击创建操作后被重定向到“/go_to_home”

尝试将规范更改为:

expect(response).to redirect_to '/go_to_home'

编辑:

这是一个真实的例子还是代码只是为了分享你想要实现的目标?我不认为 rspec 在转到“/go_to_home”后会遵循重定向,我认为这很好。

如果您正在测试创建操作,则可以测试重定向到“/go_to_home”的操作,因为这就是操作正在做的事情。然后您可以对另一个操作 go_to_home 进行另一个测试,并期望重定向到 root。

您是从其他地方调用“go_to_home”操作吗?

关于ruby-on-rails - 在 RSpec 中测试 Controller 的重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40894664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com