简体   繁体   English

Rails:测试需要访问Rails环境的帮助程序(例如request.fullpath)

[英]Rails: test a helper that needs access to the Rails environment (e.g. request.fullpath)

I have a helper that accesses request.fullpath . 我有一个访问request.fullpath的帮助器。 Within an isolated helper test, request is not available. 在隔离的帮助程序测试中, request不可用。 What should I do? 我该怎么办? Can I somehow mock it or something like that? 我能以某种方式嘲笑它或类似的东西吗?

I'm using the newest versions of Rails and RSpec. 我正在使用最新版本的Rails和RSpec。 Here's what my helper looks like: 这是我的助手的样子:

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

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

So the problematic code line is #4 where the helper needs access to the request object which isn't available in the helper spec. 因此,有问题的代码行是#4,其中帮助程序需要访问request对象,这在辅助程序规范中是不可用的。

Thanks a lot for help. 非常感谢您的帮助。

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. 只需在示例中的helper对象上调用helper方法即可。 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 will complain if your mock receives messages that you didn't stub. 如果你的模拟收到你没有存根的消息,Rspec会抱怨。 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. 如果还有其他的东西只是在帮助对象上调用你的请求帮助器方法就是你在测试中不关心,你可以通过使mock成为一个“空对象”来关闭rspec,例如。 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

在帮助器规范中,您可以使用controller.request访问请求(所以controller.request.stub(:fullpath) { "whatever" }应该工作)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM