2011-08-09 1 views
2

레일에서 다음 도우미 메서드를 테스트하려고합니다.현재 경로를 기반으로 행동을 변경하는 도우미에 대한 단위 테스트?

 def current_has_class_link(text, path, class_name="selected") 
    link_to_unless_current(text, path) do 
     link_to(text, path, :class => class_name) 
    end 
    end 

다음과 같은 테스트를 수행하려고합니다.

 describe "current_has_class_link" do 
    let(:link_path){ listings_path } 
    let(:link_text){ "Listings" } 

    it "should render a normal link if not on current path" do 
     html = "<a href=\"#{link_path}\">#{link_text}</a>" 
     current_has_class_link(link_text, link_path).should == html 
    end 

    it "should add a class if on the links path" do 
     # at this point I need to force current_path to return the same as link_path 
     html = "<a href=\"#{link_path}\" class=\"selected\">#{link_text}</a>" 
     current_has_class_link(link_text, link_path).should == html 
    end 
    end 

이제 분명히 통합 테스트를 사용할 수 있습니다. 이것을 위해 그것은 나에게는 잔인한 것처럼 보인다. current_page?를 스텁 (stub)하여 내가 필요한 것을 반환 할 수있는 방법이 있습니까?

ActionView::Helpers::UrlHelper.stub(current_page?({controller: 'listings', action: 'index'})).and_return(link_path) 

하지만 그건 내가 정말로 이해하지 못하는 오류를 준다 :

Failures: 

    1) ApplicationHelper current_has_class_link should add a class if on the links path 
    Failure/Error: ActionView::Helpers::UrlHelper.stub(current_page?({controller: 'listings', action: 'index'})).and_return(link_path) 
    RuntimeError: 
     You cannot use helpers that need to determine the current page unless your view context provides a Request object in a #request method 
    # ./spec/helpers/application_helper_spec.rb:38:in `block (3 levels) in <top (required)>' 

다른 방법이 있습니까?

답변

9

나는 동일한 문제가 있었으며 대신 테스트 레벨에서 스텁되었습니다.

self.stub!("current_page?").and_return(true) 
1

Test:Unit 내에서이 방법으로 요청을 설정하는 attr_reader를 사용할 수 있습니다. 사용

class ActiveLinkHelperTest < ActionView::TestCase 

    attr_reader :request 

    test "should render a normal link if not on current path" do 
    html = "<a href=\"#{link_path}\">#{link_text}</a>" 
    assert_equal html, current_has_class_link(link_text, link_path) 
    end 

    test "should add a class if on the links path" do 
    # Path can be set. 
    # note: the default is an empty string that will never match) 
    request.path = link_path 

    html = "<a href=\"#{link_path}\" class=\"selected\">#{link_text}</a>" 
    assert_equal html, current_has_class_link(link_text, link_path) 
    end 

end 
0

시도 :

view.stub!(:current_page?).and_return(true)