我有一个访问request.fullpath
的助手。在独立的辅助测试中,request
不可用。我该怎么办?我能嘲笑一下吗?
我使用的是Rails和RSpec的最新版本。以下是我的助手的样子:
def item(*args, &block)
# some code
if request.fullpath == 'some-path'
# do some stuff
end
end
因此,有问题的代码行是#4,其中助手需要访问助手规范中不可用的request
对象。
非常感谢你的帮助。
是的,您可以模拟请求。我在这里有一个很长的答案来描述如何做到这一点,但事实上这不一定是你想要的。
只需在示例中的helper对象上调用helper方法即可。像这样:
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
您可以将存根方法添加到返回的请求中,类似于
request.stub(:method).and_return return_value
以及mock&短截线:
request = mock('request', :method => return_value)
如果你的mock收到你没有截尾的消息,Rspec会抱怨。如果在测试中有其他你不关心的事情,只需在helper对象上调用你的request-helper方法,你就可以通过将mock设置为"null对象"来关闭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
在助手规范中,您可以使用controller.request
访问请求(因此controller.request.stub(:fullpath) { "whatever" }
应该可以工作)