2012-12-06 1 views
2

Sinatra에서 작업하면 로컬 객체 request이 생성되어 모든 뷰와 도우미가 사용할 수 있습니다. 그래서, 헬퍼 방법과 ApplicationHelper 모듈을 만들 수 있고, 도우미 메서드는 뷰에서 호출하는 경우 그들은 다시 그렇게처럼 request 객체를 호출 할 수 있습니다Ruby : 로컬 객체를 조롱하여 모듈 메소드를 테스트

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 

그래서 '테스트'코드에서 '로컬'객체를 모의 실험 할 수 있습니까?

답변

2

모의 요청 개체를 반환하는 @helper 개체에 request 메서드가 있는지 확인해야합니다.

RSpec에서는 스텁을 사용합니다. 나는 Minitest 특히 익숙하지 해요,하지만 얼핏는 (당신이 당신의 before :each@requestrequest을 변경하는 경우)이 최근 버전에서 작동 할 수 있음을 시사 :

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가 필요

때문에 스텁 된 메서드가 이미 객체에 정의되어있는 경우 Object 대신 Struct.new(:request)

@helper = Struct.new(:request).new 
대신 @helper 인스턴스를 만들 수 있습니다.

사실, 그 일을 수행하면 스텁이 전혀 필요하지 않을 수도 있습니다! 당신은 할 수있다

before :each do 
    @helper.request = MiniTest::Mock.new 
    @helper.request.expect :path_info, '/' 
end 
+0

이것은 의미가있다. 문제는 MiniTest 스텁에 메소드가 이미 있어야한다는 것이고, 모듈에 정상적으로 정의하면 실제 앱에서 원하는 것을 오버라이드한다. 그래서, 이것은 거의 나를 거기에 데려 간다, 지금 나는 잠깐 그것을 궁리 할 필요가있다 – Andrew

+0

아하, 오케이. @helper = Struct.new (: request) .new' –

+0

아, 그게 내가 가진 것보다 훨씬 좋은 생각 일거야! 나는 생각하고 있었다. @helper.instance_eval {def request; 무; 끝;}'... 당신의 방법이 진짜 빨리 작동하는지 보자. – Andrew

관련 문제