2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Flaky Test】運が悪かったら落ちてしまうテストに遭遇した

Last updated at Posted at 2025-08-05

前提

  • RSpecでのテスト
  • 対象のテストはModelのテストで、超端的に言うと「〇〇は文字列だったらダメ!」というもの。
  • FakerのFaker::Lorem.charactersを用いてランダムな文字列生成してテストにかけていた。

あ...ありのまま今起こったことを話すぜ!(ポルナレフ)

案件先でフロントエンドの修正をしていたら、なぜかCIでRSpecModelテストが落ちた。
「文字列を許容しない」というテストで、Faker::Lorem.characters(number: 3)を使って文字列を生成していたはずなのに、なぜかバリデーションを通過してしまっていた。

なぜこんなことが起こった?

調べてみると、Fakerが生成した文字列が「"625"」のような数字のみの文字列だった。

どうやらActiveRecordinteger型のカラムに文字列を代入する際、自動的に数値に変換するらしい。

つまり

  1. Faker::Lorem.characters(number: 3)"625"(たまたま数字のみ)
  2. ActiveRecordの型キャスト → 625(integer)
  3. バリデーション通過 → テスト失敗:frowning2:

たまたま運が悪くテストが落ちてしまったのである:stuck_out_tongue_closed_eyes:

解決策

一旦確実に文字列を生成させるようにFaker::Alphanumeric.alpha(number: 3)で文字列を生成させることにした。

教訓

  • Faker::Lorem.charactersは英数字からランダム生成するため、約2% の確率で 数字のみになる。
  • ActiveRecordは親切すぎて文字列を勝手に数値変換する

まとめ

image.png

というか以前もこういう「Flaky Test」に遭遇したような...?
よくあることなのかな

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?