帮助器的单元测试,它根据当前路径改变行为?

Dav*_*ite 2 unit-testing rspec ruby-on-rails rspec2 ruby-on-rails-3

我正在尝试在rails中测试以下帮助器方法:

  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
Run Code Online (Sandbox Code Playgroud)

我正在尝试进行类似这样的测试:

  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
Run Code Online (Sandbox Code Playgroud)

现在显然我可以使用集成测试,但这似乎对我来说太过分了.有没有办法我可以存根current_page?以便它能够返回我需要的东西?

我试着这样做

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

但这给了我一个我不太懂的错误:

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)>'
Run Code Online (Sandbox Code Playgroud)

还有另外一种方法吗?

Gar*_*ran 10

我遇到了同样的问题,而是在测试级别将其删除.

self.stub!("current_page?").and_return(true)
Run Code Online (Sandbox Code Playgroud)