Rails Tutorial 6.0 Chapter 7 7.3.4 Test at the time of failure Record of stumbling in the last exercise
"Write a test for the error message implemented in Listing 7.20. I'll leave it to you to test it in detail. I've provided a template for Listing 7.25 for your reference."
Use assert_select It's a good idea to check the HTML structure for improper login-specific elements.
Contents of the partial created immediately before (This content is inserted in new.html.erb)
ruby:/sample_app/app/views/shared/_error_messages.html.erb
<% if @user.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-danger">
      The form contains <%= pluralize(@user.errors.count, "error") %>.
    </div>
    <ul>
    <% @user.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
  </div>
<% end %>
If @ user.errors exists, A div tag containing a specific class ("alert" & "alert-danger"), id ("error_explanation") is expanded
As long as this is included in the final HTML passed to the browser, assert_select'Selector (class: div.class, id: div # id)' Confirm it with
The completed form is as follows
/sample_app/test/integration/users_signup_test.rb
require 'test_helper'
class UsersSignupTest < ActionDispatch::IntegrationTest
  test "invalid signup information" do
    assert_no_difference 'User.count' do
      post users_path, params: { user: { name: "",
                                         email: "user@invalid",
                                         password: "foo",
                                         password_confirmation: "bar"} }
    end
    assert_template 'users/new'
    assert_select 'div.alert'
    assert_select 'div.alert-danger'
    assert_select 'div#error_explanation'
  end
end
The structure verified by assert_select,
Visually shown in Google Chrome developer tools

that's all
Use "" and "" properly I feel like "" is preferred when explicitly indicating that it is a string, The selector is specified as'''
Recommended Posts