0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

railsチュートリアル第七章 実際のユーザー登録 成功時のテスト

Posted at

実際のユーザー登録

今まで実験でユーザー登録をしているので一度リセット

$ rails db:migrate:reset

rails sでサーバーを起動させる。
新しくユーザー情報を登録し、flashのメッセージを表示させる
再読み込みするとメッセージがなくなる。

演習

1.Railsコンソールを使って、新しいユーザーが本当に作成されたのかもう一度チェックしてみましょう。結果は、リスト 7.30のようになるはずです。

>> User.all
  User Load (0.2ms)  SELECT "users".* FROM "users" LIMIT ?  [["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<User id: 1, name: "a", email: "abc@def.com", created_at: "2021-10-05 04:11:41", updated_at: "2021-10-05 04:11:41", password_digest: [FILTERED]>]>

2.自分のメールアドレスでユーザー登録を試してみましょう。既にGravatarに登録している場合、適切な画像が表示されているか確認してみてください

上と同じことだと思ってやらなかった。

成功時のテスト

有効なユーザー登録に対するテスト

test/integration/users_signup_test.rb

require 'test_helper'
.
.
.
  test "valid signup information" do
    get signup_path
    assert_difference 'User.count', 1 do
    # 一つだけしか登録されてないことを確かめるのかな?
    # 第二引数でデータベースとの差異は1である。
      post users_path, params: { user: { name:  "Example User",
                                         email: "user@example.com",
                                         password:              "password",
                                         password_confirmation: "password" } }
    end
    follow_redirect!
    # POSTリクエストを送信した結果を見て、指定されたリダイレクト先に移動するメソッド
    assert_template 'users/show'
    # showアクションのビューを表示させる。
  end
end

演習

1.7.4.2で実装したflashに対するテストを書いてみてください。どのくらい細かくテストするかはお任せします。リスト 7.32に最小限のテンプレートを用意しておいたので、参考にしてください((コードを書き込む)の部分を適切なコードに置き換えると完成します)。ちなみに、テキストに対するテストは壊れやすいです。文量の少ないflashのキーであっても、それは同じです。筆者の場合、flashが空でないかをテストするだけの場合が多いです

require 'test_helper'

class UsersSignupTest < ActionDispatch::IntegrationTest
.
.
.
  test "valid signup information" do
    get signup_path
    assert_difference 'User.count', 1 do
    # 
    # 第二引数でデータベースとの差異は1である。
      post users_path, params: { user: { name:  "Example User",
                                         email: "user@example.com",
                                         password:              "password",
                                         password_confirmation: "password" } }
    end
    follow_redirect!
    # POSTリクエストを送信した結果を見て、指定されたリダイレクト先に移動するメソッド
    assert_template 'users/show'
    # showアクションのビューを表示させる。
    assert_not flash.nil?
    #flashがnilクラスじゃないよね? flashはハッシュだからかな?
    
  end
end

2.本文中でも指摘しましたが、flash用のHTML(リスト 7.29)は読みにくいです。より読みやすくしたリスト 7.33のコードに変更してみましょう。変更が終わったらテストスイートを実行し、正常に動作することを確認してください。なお、このコードでは、Railsのcontent_tagというヘルパーを使っています。

<!DOCTYPE html>
<html>
  <head>
    <title><%= full_title(yield(:title)) %></title>
    <%= render 'layouts/rails_default' %>
    <%= render 'layouts/shim' %>
  </head>
  <body>
    <%= render 'layouts/header' %>
    <div class="container">
      <% flash.each do |message_type, message| %>
        <%= content_tag(:div, message, class: "alert alert-#{message_type}") %>
        <!--これがデータ送信成功時メッセージのためのHTML-->
        <!--message_typeにsuccess, messageに成功時メッセージ-->
      <% end %>
      <%= yield %>
      <%= render 'layouts/footer' %>
      <%= debug(params) if Rails.env.development? %>
      <!--デバッグ情報はRailsの3つのデフォルト環境のうち、開発環境(development)だけで表示されるようになります-->
    </div>
  </body>
</html>

3.リスト 7.26のリダイレクトの行をコメントアウトすると、テストが失敗することを確認してみましょう。

ERROR["test_valid_signup_information", #<Minitest::Reporters::Suite:0x000055cc8f4de6d8 @name="UsersSignupTest">, 1.726447963000055]
 test_valid_signup_information#UsersSignupTest (1.73s)
RuntimeError:         RuntimeError: not a redirect! 204 No Content
            test/integration/users_signup_test.rb:30:in `block in <class:UsersSignupTest>'

  21/21: [==============================] 100% Time: 00:00:01, Time: 00:00:01

Finished in 1.80173s
21 tests, 41 assertions, 0 failures, 1 errors, 0 skips

RuntimeError: not a redirect! 204 No Content
エラーの意味がちょっとわからない。

4.リスト 7.26で、@user.saveの部分をfalseに置き換えたとしましょう(バグを埋め込んでしまったと仮定してください)。このとき、assert_differenceのテストではどのようにしてこのバグを検知するでしょうか? テストコードを追って考えてみてください。

ubuntu:~/environment/sample_app (sign-up) $ rails t
Running via Spring preloader in process 6196
Started with run options --seed 35811

 FAIL["test_valid_signup_information", #<Minitest::Reporters::Suite:0x000055cc8fc47208 @name="UsersSignupTest">, 1.7643740539997452]
 test_valid_signup_information#UsersSignupTest (1.76s)
        "User.count" didn't change by 1.
        Expected: 1
          Actual: 0
        test/integration/users_signup_test.rb:22:in `block in <class:UsersSignupTest>'

  21/21: [==============================] 100% Time: 00:00:01, Time: 00:00:01

Finished in 1.87888s
21 tests, 41 assertions, 1 failures, 0 errors, 0 skips
"User.count" didn't change by 1.
        Expected: 1
          Actual: 0

@user.saveで保存してないから0になるからかな?

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?