0
0

More than 3 years have passed since last update.

Railsチュートリアル 第12章 パスワードの再設定 - 「ログイン画面に、パスワード再設定用のリンクが存在すること」に対するテストを実装する

Last updated at Posted at 2019-12-11

テストコード

変更対象となるテストコードはtest/integration/users_login_test.rbです。

test/integration/users_login_test.rb
  class UsersLoginTest < ActionDispatch::IntegrationTest
    ...略

    test "login with invalid information" do
      get login_path
      assert_template 'sessions/new'
+     assert_select "a[href=?]", new_password_reset_path
      post login_path, params: { session: { email: "", password: ""} }
      assert_template 'sessions/new'
      assert_not flash.empty?
      assert_select 'div.alert-danger'
      get root_path
      assert flash.empty?
    end

    ...略
  end

テストを実行してみる

この時点でテストは成功します。

# rails test
Running via Spring preloader in process 14842
Started with run options --seed 21965

  46/46: [=================================] 100% Time: 00:00:04, Time: 00:00:04

Finished in 4.81443s
46 tests, 198 assertions, 0 failures, 0 errors, 0 skips

このテストは、どうすれば失敗するようになるのか

例えば以下のようにapp/views/sessions/new.html.erbを変更すると…

app/views/sessions/new.html.erb
  <% provide(:title, "Log in") %>
  <h1>Log in</h1>

  <div class="row">
    <div class="col-md-6 col-md-offset-3">
      <%= form_for(:session, url: login_path) do |f| %>

        <%= f.label :email %>
        <%= f.email_field :email, class: 'form-control' %>

        <%= f.label :password %>
-       <%= link_to "(forgot password)", new_password_reset_path %>
+       <%# <%= link_to "(forgot password)", new_password_reset_path %> %>
        <%= f.password_field :password, class: 'form-control' %>

        <%= f.label :remember_me, class: "checkbox inline" do %>
          <%= f.check_box :remember_me %>
          <span>Remember me on this computer</span>
        <% end %>

        <%= f.submit "Log in", class: "btn btn-primary" %>
      <% end %>

      <p>New user? <%= link_to "Sign up now!", signup_path %></p>
    </div>
  </div>

以下のようにテストが失敗します。

# rails test test/integration/users_login_test.rb:12
Running via Spring preloader in process 14868
Started with run options --seed 5918

 FAIL["test_login_with_invalid_information", UsersLoginTest, 2.484278399962932]
 test_login_with_invalid_information#UsersLoginTest (2.48s)
        Expected at least 1 element matching "a[href="/password_resets/new"]", found 0..
        Expected 0 to be >= 1.
        test/integration/users_login_test.rb:12:in `block in <class:UsersLoginTest>'

  4/4: [===================================] 100% Time: 00:00:02, Time: 00:00:02

Finished in 2.48610s
1 tests, 2 assertions, 1 failures, 0 errors, 0 skips

「/password_resets/new へのリンクが1つも描画されていない」という趣旨のメッセージですね。想定したテストが正しく実装されていると言えそうです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0