2011-08-09 51 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?,以便它返回我需要的東西?

我試圖做

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)