2

在 Sinatra 中工作时,会创建一个本地对象request,并使其可供所有视图和助手使用。因此,我可以ApplicationHelper使用辅助方法创建一个模块,如果在视图中调用辅助方法,它们可以依次调用request对象,如下所示:

module ApplicationHelper
  def nav_link_to(text,path)
    path == request.path_info ? klass = 'class="current"' : klass = ''
    %Q|<a href="#{path}" #{klass}>#{text}</a>|
  end
end

现在,我想对此进行测试,但在我的测试中,该request对象不存在。我试图嘲笑它,但这没有用。到目前为止,这是我的测试:

require 'minitest_helper'
require 'helpers/application_helper'

describe ApplicationHelper do

  before :all do
    @helper = Object.new
    @helper.extend(ApplicationHelper)
  end

  describe "nav links" do
    before :each do
      request = MiniTest::Mock.new
      request.expect :path_info, '/'
    end

    it "should return a link to a path" do
      @helper.nav_link_to('test','/test').must_equal '<a href="/test">test</a>'
    end

    it "should return an anchor link to the current path with class 'current'" do
      @helper.nav_link_to('test','/').must_equal '<a href="test" class="current">test</a>'
    end
  end
end

那么,您如何模拟一个“本地”对象,以便您的测试代码可以调用它?

4

1 回答 1

2

您需要确保request您的@helper对象上有一个返回模拟请求对象的方法。

在 RSpec 我只是存根它。我对 Minitest 不是特别熟悉,但快速浏览一下表明这可能在最近的版本中有效(如果你在你的 中更改request为):@requestbefore :each

it "should return a link to a path" do
  @helper.stub :request, @request do
    @helper.nav_link_to('test','/test').must_equal '<a href="/test">test</a>'
  end
end

更新

由于 Minitest 要求已经在对象上定义了存根方法,因此您可以创建@helper一个实例Struct.new(:request)而不是Object,即

@helper = Struct.new(:request).new

实际上,这样做之后,您可能根本不需要存根!你可以做

before :each do
  @helper.request = MiniTest::Mock.new
  @helper.request.expect :path_info, '/'
end
于 2012-12-06T00:38:07.243 回答