「ユーザーが削除されると、当該ユーザーのマイクロポストも同時に破棄されていること」に対するテストを実装する
テストの内容は以下のようになります。名前は「associated microposts should be destroyed」とします。
test "associated microposts should be destroyed" do
@user.save
@user.microposts.create!(content: "Lorem ipsum")
assert_difference 'Micropost.count', -1 do
@user.destroy
end
end
テストを追加する箇所は、test/models/user_test.rb
となります。test/models/micropost_test.rb
ではありませんので注意が必要です。
test/models/user_test.rb
require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = User.new(name: "Example User", email: "user@example.com",
password: "foobar", password_confirmation: "foobar")
end
...略
+
+ test "associated microposts should be destroyed" do
+ @user.save
+ @user.microposts.create!(content: "Lorem ipsum")
+ assert_difference 'Micropost.count', -1 do
+ @user.destroy
+ end
+ end
end
「ユーザーが削除されると、当該ユーザーのマイクロポストも同時に破棄されていること」に対するテストを追加した時点でのテストの結果
# rails test test/models/user_test.rb
Running via Spring preloader in process 1718
Started with run options --seed 27055
FAIL["test_associated_microposts_should_be_destroyed", UserTest, 1.2237603999965359]
test_associated_microposts_should_be_destroyed#UserTest (1.22s)
"Micropost.count" didn't change by -1.
Expected: 4
Actual: 5
test/models/user_test.rb:81:in `block in <class:UserTest>'
13/13: [=================================] 100% Time: 00:00:01, Time: 00:00:01
Finished in 1.61126s
13 tests, 22 assertions, 1 failures, 0 errors, 0 skips
以下のようなメッセージが表示されて、テストが失敗しています。
"Micropost.count" didn't change by -1.
「マイクロポストの数が1つ減っていなければならないのに、1つ減っていない」という趣旨のメッセージですね。想定通りの動作です。
「ユーザーが削除されると、当該ユーザーのマイクロポストも同時に破棄される」という実装を追加する
has_many
メソッドにdependent :destroy
オプションを追加すれば、上記の機能を実装することができます。具体的には、app/models/user.rb
を以下のように変更します。
app/models/user.rb
class User < ApplicationRecord
- has_many :microposts
+ has_many :microposts, dependent: :destroy
...略
end
「ユーザーが削除されると、当該ユーザーのマイクロポストも同時に破棄される」という実装を追加した時点で、再びテストを実行してみる
test/models/user_test.rb
を対象とするテストを再度実施してみましょう。
# rails test test/models/user_test.rb
Running via Spring preloader in process 1731
Started with run options --seed 63273
13/13: [=================================] 100% Time: 00:00:01, Time: 00:00:01
Finished in 1.56839s
13 tests, 22 assertions, 0 failures, 0 errors, 0 skips
無事テストが成功するようになりました。