【发布时间】:2011-08-09 10:44:48
【问题描述】:
我正在尝试在 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
我正在尝试做一个类似这样的测试:
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)>'
还有其他方法吗?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 unit-testing rspec rspec2