assert_select计数预计正好 2 个元素匹配 "a[href=" / "]" ,找到 4



我正在尝试检查与root_path路由的链接。我的问题是,当assert_select计数时,为什么我的_header.html.erb文件中的每个路线都会加倍。root_path在页面中使用了两次<%= link_to "sample app", root_path, id: "logo" %><li> <%= link_to "Home", root_path %> </li>,那么它为什么给我4?我是Rails的新手,我关注Michael Hartl的教程。

这是我进行集成测试的代码:

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

这是我的HTML文件(_header.html.erb)的部分代码:

<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时,它会给我1个故障,即:

失败[" test_layout_links",sitelayouttest,2016-06-15 20:11:58 0800] test_layout_links#sitelayouttest(1465992718.76S)

正好期望与" a [href ="/")相匹配的2个元素,发现4 ..

预期:2

实际:4

test/intermation/site_layout_test.rb:6:在`block in&lt; class; class:sitelayouttest>'

您可以将测试更改为:

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

它应该起作用。这是一个很好的资源,可以帮助解决此类问题:https://gist.github.com/zhengjia/428105

在,

中使用此代码

_header.html.erb:

  • &lt;%= link_to" home",root_path%>
  • &lt;%= link_to" help",help_path%>
  • _footer.html.erb:

  • &lt;%= link_to" about",about_path%>
  • &lt;%= link_to"联系",contact_path%>
  • 最新更新