简体   繁体   中英

assert_select and assert_template test. What is it doing?

This is from the Hartl Tutorial:

Here is my test:

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

Here is my code which is the index.html.erb. I am not showing the 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 %>

What is the assert_template doing?

This is from the docs:

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

Is it checking the name of the view or partial? Or is it checking the URL?

What is assert_select doing here? This is from the docs:

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

Is it checking that there exists a <div class=pagination> on the page? What is it doing? What is it asserting?

First send a get request to the users path

get users_path

After this check that the rendered template is the right one.

assert_template 'users/index'

It is not checking directly the url, but if you have any problems with routing, you won't get the right template.

Then, for testing the pagination, it checks that in the template exists a div element with class="pagination", this element is added by the paginations gems used.

assert_select 'div.pagination'

assert_select gets the html elements of the template and check if a given element is present.

Finally, it gets the users of the first page of the pagination (the ones should be on the index page) and for each one checks that in the page there is an a element linking to the url of the user and enclosing the text corresponding to the user name.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM