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@requestた場合before :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では、スタブメソッドがオブジェクトにすでに定義されている必要があるため、の代わりにのインスタンスを作成できます@helperStruct.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 に答える