assert_select count预计恰好有2个元素匹配“a [href =”/“]”,找到4

时间:2016-06-15 22:01:43

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

我正在尝试检查有多少链接路由到root_path。我的问题是为什么我的_header.html.erb文件中的每个路由都被加倍assert_select。页面中root_path使用<%= link_to "sample app", root_path, id: "logo" %>两次<li> <%= link_to "Home", root_path %> </li>4,为什么它会给我require 'test_helper' class SiteLayoutTest < ActionDispatch::IntegrationTest test "layout links" do get root_path assert_template 'static_pages/home' assert_select "a[href=?]", root_path, count:2 assert_select "a[href=?]", help_path assert_select "a[href=?]", about_path assert_select "a[href=?]", contact_path end end ?我是rails的新手,我正在关注Michael Hartl的教程。

以下是我的集成测试代码:

_header.html.erb

这是我的HTML文件(<header class="nav-bar navbar-fixed-top navbar-inverse" id="header"> <div class="container"> <%= link_to "sample app", root_path, id: "logo" %> <nav> <ul class="nav navbar-nav navbar-right"> <li> <%= link_to "Home", root_path %> </li> <li> <%= link_to "Help", help_path %> </li> <li> <%= link_to "Log in", "#" %> </li> </ul> </nav> </div> </header> )的部分代码:

bundle exec rake test

当我运行switchMap时,它给了我1次失败:

  

失败[“test_layout_links”,SiteLayoutTest,2016-06-15 20:11:58 +0800]   test_layout_links #SiteLayoutTest(1465992718.76s)

     

预计恰好2个元素匹配“a [href =”/“]”,找到4 ..

     

预计:2

     

实际:4

     

test / integration / site_layout_test.rb:6:在`block in&lt; class:SiteLayoutTest&gt;'

2 个答案:

答案 0 :(得分:0)

您可以将测试更改为:

within(:css, "ul") do
      assert_select "a[href=?]", root_path, count:2
end

它应该有效。以下是帮助解决此类问题的良好资源:https://gist.github.com/zhengjia/428105

答案 1 :(得分:0)

使用此代码,

_header.html.erb:

  • &lt;%= link_to“Home”,root_path%&gt;
  • &lt;%= link_to“帮助”,help_path%&gt;
  • _footer.html.erb:

  • &lt;%= link_to“关于”,about_path%&gt;
  • &lt;%= link_to“联系人”,contact_path%&gt;