assert_select 和 assert_template 测试。它在做什么?

assert_select and assert_template test. What is it doing?

这来自 Hartl 教程:

这是我的测试:

test "index including pagination" do
    log_in_as(@user)
    get users_path
    assert_template 'users/index'
    assert_select 'div.pagination'
    User.paginate(page: 1).each do |user|
      assert_select 'a[href=?]', user_path(user), text: user.name
  end
end

这是我的代码 index.html.erb。我没有显示 application.html.erb.

<% provide(:title, 'All users') %>
<h1>All users</h1>

<%= will_paginate %>

<ul class="users">
  <% @users.each do |user| %>
    <li>
      <%= gravatar_for user, size: 50 %>
      <%= link_to user.name, user %>
    </li>
  <% end %>
</ul>

<%= will_paginate %>

assert_template 在做什么?

这是来自文档:

Asserts that the request was rendered with the appropriate template file or partials.

它是检查视图的名称还是局部的?或者它正在检查 URL?

assert_select 在这里做什么?这是来自文档:

An assertion that selects elements and makes one or more equality tests.

是否检查页面上是否存在<div class=pagination>?它在做什么?它在断言什么?

先向users路径发送get请求

get users_path

在此之后检查呈现的模板是否正确。

assert_template 'users/index'

它不会直接检查 url,但如果您在路由方面有任何问题,您将无法获得正确的模板。

然后,为了测试分页,它检查模板中是否存在 div 元素 class="pagination",该元素由使用的分页 gems 添加。

assert_select 'div.pagination'

assert_select 获取模板的 html 个元素并检查给定元素是否存在。

最后,它获取分页第一页的用户(应该在索引页上),并为每个用户检查页面中是否有一个元素链接到 url用户名并附上与用户名对应的文本。

User.paginate(page: 1).each do |user|
  assert_select 'a[href=?]', user_path(user), text: user.name