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
그래서 '테스트'코드에서 '로컬'객체를 모의 실험 할 수 있습니까?
이것은 의미가있다. 문제는 MiniTest 스텁에 메소드가 이미 있어야한다는 것이고, 모듈에 정상적으로 정의하면 실제 앱에서 원하는 것을 오버라이드한다. 그래서, 이것은 거의 나를 거기에 데려 간다, 지금 나는 잠깐 그것을 궁리 할 필요가있다 – Andrew
아하, 오케이. @helper = Struct.new (: request) .new' –
아, 그게 내가 가진 것보다 훨씬 좋은 생각 일거야! 나는 생각하고 있었다. @helper.instance_eval {def request; 무; 끝;}'... 당신의 방법이 진짜 빨리 작동하는지 보자. – Andrew