ken2merのブログ

Webエンジニア, Ruby on Rails, Go

Railsアプリケーションでsteep checkを試す

Ruby 3関連でRailsアプリケーション上で何か試したいと思っていたら以下の記事を発見したので、これをそのまま試してみる。

pocke.hatenablog.com

Gemfileに必要なGemを追加

https://github.com/Ken2mer/rails_master_test_app/commit/9d12ab40fa3aaadf18fcb823c52ddae4ea0bfb66

Rake Taskの追加

https://github.com/Ken2mer/rails_master_test_app/commit/479b06a43c9badf91b42f9acebd4a8646db6d60a

Rake Taskの実行(bin/rake rbs_rails:all)

https://github.com/Ken2mer/rails_master_test_app/commit/cdd9d753eb8665ab7eb70bb8e2124db969b60bed

このコミットから、元記事の解説と実際に行われた処理を照らし合わせてみる。

RBS Railsから、解析に必要なRBSファイルをコピーしてくる

Rake Taskの中で以下の処理が呼ばれるよう。 https://github.com/pocke/rbs_rails/blob/1b6e4f7bc21624c9fabac122152e97794c5ca1b7/lib/rbs_rails.rb#L14-L18

上記により「解析に必要なRBSファイル」は以下のディレクトリ配下のものを示すことがわかる。 https://github.com/pocke/rbs_rails/tree/master/assets/sig

データベースのスキーマ定義から、対応するモデルのRBSファイルを生成する

今回使用したアプリケーションに含まれるモデルは UserMessage のみ。それに対応するRBSファイルが生成されているのがわかる。

routes定義から、パスヘルパーのRBSファイルを生成する

ルーティングの定義をしていなかったので確認できず。あとでやってみる。

git submoduleを使ってgem_rbsをダウンロード

https://github.com/Ken2mer/rails_master_test_app/commit/1de8e4c56098fe8ab980f1dc0197d375c8cb7931

rbs validate のエラー解消

https://github.com/Ken2mer/rails_master_test_app/commit/0f2f461fea069b889a47de368100ef2ecede356d

このコミットでやっているのは、元記事でも触れられている ApplicationRecord の型定義と、まだ未対応っぽいActiveStorageの型定義の手動追加である。これで一旦 rbs validate コマンドを通すことができた。

Steepfileの設定

https://github.com/Ken2mer/rails_master_test_app/commit/bf45d698aab6b55ed08668ec2caa570d2ff62856

このコミットではSteepfileは元記事と同じ内容のままで使っている。また steep init コマンドで生成できるとあり、その場合はデフォルトで以下のような内容となる。

# target :lib do
#   signature "sig"
#
#   check "lib"                       # Directory name
#   check "Gemfile"                   # File name
#   check "app/models/**/*.rb"        # Glob
#   # ignore "lib/templates/*.rb"
#
#   # library "pathname", "set"       # Standard libraries
#   # library "strong_json"           # Gems
# end

# target :spec do
#   signature "sig", "sig-private"
#
#   check "spec"
#
#   # library "pathname", "set"       # Standard libraries
#   # library "rspec"
# end

Steepの実行(bundle exec steep check)

このコマンドで型検査ができる。いまのリポジトリの状態では以下のような出力が得られた。

% bundle exec steep check
app/models/message.rb:2:2: NoMethodError: type=singleton(::Message), method=has_many_attached (has_many_attached :images)
app/models/user.rb:2:2: NoMethodError: type=singleton(::User), method=has_one_attached (has_one_attached :avatar)

ActiveStorage関連のメソッドで型エラーが出ていることがわかる。これに対応する型定義を書いていくことになるということか。

やり残し

bin/rake rbs_rails:all の実行時にエラーが出ていた。 https://github.com/Ken2mer/rails_master_test_app/commit/c81966d029b2029c17461942d375d6ff1ea4d7bb

メッセージは PG::UndefinedTable: ERROR: relation action_text_rich_texts does not exist というもの。

action_text_rich_texts というテーブル定義がないとのこと。これはActionText関連のものっぽいので、とりあえず action_text:install してみたが解消されず。というのが上記のコミット。

action_text:installcreate_action_text_tables.action_text.rbマイグレーションファイルができていないのがおかしそう。なので再調査してみる必要がある。

参考情報