Rails:测试需要访问 Rails 环境的帮助程序(例如 request.fullpath) [英] Rails: test a helper that needs access to the Rails environment (e.g. request.fullpath)
问题描述
我有一个访问 request.fullpath
的助手.在隔离的帮助程序测试中,request
不可用.我应该怎么办?我可以以某种方式嘲笑它或类似的东西吗?
I have a helper that accesses request.fullpath
. Within an isolated helper test, request
is not available. What should I do? Can I somehow mock it or something like that?
我使用的是最新版本的 Rails 和 RSpec.这是我的助手的样子:
I'm using the newest versions of Rails and RSpec. Here's what my helper looks like:
def item(*args, &block)
# some code
if request.fullpath == 'some-path'
# do some stuff
end
end
所以有问题的代码行是 #4,其中帮助程序需要访问在帮助程序规范中不可用的 request
对象.
So the problematic code line is #4 where the helper needs access to the request
object which isn't available in the helper spec.
非常感谢您的帮助.
推荐答案
是的,您可以模拟请求.我在这里有一个很长的答案来描述如何做到这一点,但实际上这不一定是您想要的.
Yes, you can mock the request. I had a whole long answer here describing how to do that, but in fact that's not necessarily what you want.
只需在示例中的辅助对象上调用辅助方法即可.像这样:
Just call your helper method on the helper object in your example. Like so:
describe "#item" do
it "does whatever" do
helper.item.should ...
end
end
这将使您能够访问测试请求对象.如果你需要为请求路径指定一个特定的值,你可以这样做:
That will give you access to a test request object. If you need to specify a specific value for the request path, you can do so like this:
before :each do
helper.request.path = 'some-path'
end
<小时>
实际上,为了完整起见,让我包括我的原始答案,因为根据您尝试执行的操作,它可能仍然有帮助.
Actually, for completeness, let me include my original answer, since depending on what you're trying to do it might still be helpful.
以下是模拟请求的方法:
Here's how you can mock the request:
request = mock('request')
controller.stub(:request).and_return request
同样可以在返回的请求中添加存根方法
You can add stub methods to the returned request similarly
request.stub(:method).and_return return_value
以及模拟 & 的替代语法在一行中存根:
And alternative syntax to mock & stub all in one line:
request = mock('request', :method => return_value)
如果你的模拟收到你没有存根的消息,Rspec 会抱怨.如果还有其他事情,只需在助手对象上调用您的请求助手方法,而您在测试中并不关心,您可以通过使模拟成为空对象"来关闭 rspec,例如.像这样
Rspec will complain if your mock receives messages that you didn't stub. If there's other stuff Just call your request helper method on the helper object is doing that you don't care about in your test, you can shut rspec up by making the mock a "null object",example. like Like so
request = mock('request').as_null_object
看起来你可能需要通过这个特定的测试是这样的:
It looks like all you probably need to get your specific test passing is this:
describe "#item" do
let(:request){ mock('request', :fullpath => 'some-path') }
before :each do
controller.stub(:request).and_return request
end
it "does whatever"
end
这篇关于Rails:测试需要访问 Rails 环境的帮助程序(例如 request.fullpath)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!