0
0

【RSpec】2次元hashでincludeマッチャを使うときの注意点

Posted at

直面したエラー

$ docker-compose exec api bin/rspec --only-failure
Failure/Error:
        expect(JSON.parse(response.body)).to include({
            'user' => {
                'id' => user.id,
                'user_name' => user.user_name,
                'email' => user.email,
             }
        })
     
        expected {
            "user" => {
                "created_at" => "2024-05-29T10:00:43.356+09:00",
                "deleted_at" => nil,
                "email" => "test@gmail.com",
                "id" => "123",
                "updated_at" => "2024-05-29T10:00:43.356+09:00",
                "user_name" => "test_user",
            }
        }
        to include {
            "user" => {
                "id" => "123",
                "user_name" => "test_user",
                "email" => "test@gmail.com",
            }
        }

原因は,includeマッチャはトップレベルのキーのマッチングを行うからでした.
つまり,上例のuserincludeとして部分一致でマッチングを行いますが,それ以下のid,user_name, email,updated_at,deleted_at,created_atは全て一致する必要があるためエラーになっていました.

解決策

しかし今回はid,user_name,emailで部分一致を行いたかったので,以下で対応しました.

	expect(JSON.parse(response.body)['user']).to include({
		'id' => user.id,
		'user_name' => user.user_name,
		'email' => user.email,
		'picture' => user.picture
	})

最後に

間違っている点があればコメントでご教授いただけると幸いです.

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