gpt4 book ai didi

ruby-on-rails - rails : test a helper that needs access to the Rails environment (e. g。请求.完整路径)

转载 作者:行者123 更新时间:2023-11-28 19:49:40 24 4
gpt4 key购买 nike

我有一个访问 request.fullpath 的助手。在孤立的帮助程序测试中,request 不可用。我应该怎么办?我能以某种方式 mock 它或类似的东西吗?

我使用的是最新版本的 Rails 和 RSpec。这是我的助手的样子:

def item(*args, &block)
# some code

if request.fullpath == 'some-path'
# do some stuff
end
end

所以有问题的代码行是#4,帮助程序需要访问 request 对象,这在帮助程序规范中不可用。

非常感谢您的帮助。

最佳答案

是的,您可以模拟请求。我在这里有一个很长的答案,描述了如何做到这一点,但实际上这不一定是您想要的。

只需在示例中的辅助对象上调用辅助方法即可。像这样:

describe "#item" do
it "does whatever" do
helper.item.should ...
end
end

这将使您能够访问测试请求对象。如果您需要为请求路径指定一个特定的值,您可以这样做:

before :each do
helper.request.path = 'some-path'
end

实际上,为了完整起见,让我包含我的原始答案,因为根据您尝试执行的操作,它可能仍然有帮助。

这是模拟请求的方法:

request = mock('request')
controller.stub(:request).and_return request

您可以类似地向返回的请求添加 stub 方法

request.stub(:method).and_return return_value

以及在一行中模拟和 stub 的替代语法:

request = mock('request', :method => return_value)

如果你的 mock 收到你没有 stub 的消息,Rspec 会提示。如果还有其他的东西,只需在 helper 对象上调用你的 request helper 方法,你在测试中不关心,你可以通过使模拟成为“空对象”来关闭 rspec,例如。像这样

 request = mock('request').as_null_object

看起来你可能需要让你的特定测试通过是这样的:

describe "#item" do
let(:request){ mock('request', :fullpath => 'some-path') }

before :each do
controller.stub(:request).and_return request
end

it "does whatever"
end

关于ruby-on-rails - rails : test a helper that needs access to the Rails environment (e. g。请求.完整路径),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12528001/

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