0
0

More than 1 year has passed since last update.

【RSpec】expected `User.count` to have changed by 1, but was changed by 0というエラーの解決方法

Posted at

対象者

  • タイトル記載のエラーに苦しんでる方
  • RSpecテストのコードを書いている方

目的

  • エラーを解決して、テストを正常に稼働させる

実際の手順と実例

1.前提と現状

スクリーンショット 2021-09-21 21.18.25.png

ユーザーの新規登録が成功するかどうかのテスト実行時にこのようなエラーがでました、、、

直訳すると

User.count "が1だけ変化したと思ったら、0だけ変化していた。

 
推測すると新規登録が正常に行えず、Userが1人増えなかったということだと思いました。

該当ソースコードは以下の通り

spec/system/before_login_spec.rb
  describe "ユーザー新規登録のテスト" do
      before do
        visit new_user_registration_path
      end

      (中略)

        context "新規登録成功のテスト" do
        before do
          fill_in "user[name]", with: Faker::Lorem.characters(number: 10)
          fill_in "user[email]", with: Faker::Internet.email
          fill_in "user[password]", with: "password"
          fill_in "user[password_confirmation]", with: "password"
        end

        it " 新規登録が正しく実行される" do
          expect do
            click_button "登録する"
          end.to change(User, :count).by(1)
        end
     end
  end

2.結論(解決策)

バリデーショをチェックすること

単純なミスでした、、、、、
バリデーションにひっかかっていたために新規投稿が成功せずにエラーを吐いていたので、バリデーションを見直すと解決できると思います。

3.原因

私の上記例で例えると、
新規登録時に2文字以上のnicknameが必須項目になっていたので、前提の条件(before ~ end )に

fill_in "user[nickname]", with: Faker::Lorem.characters(number: 10)

を追加して解決できました。

参考にさせて頂いた記事

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