この記事は
ruby-jp の #rails チャンネルで知った Rails のバグ報告テンプレートが目からウロコだった話をします。bug_report_templates/active_record_gem.rb の存在を知らない方向けです。
概要
気軽に ActiveRecord の動作を確かめたい
ちょっと ActiveRecord の動作を確かめたい。でも手元にちょうといい Rails プロジェクトがない。rails new するのは面倒だ……。マイグレーションも書かなきゃ……。
そんなとき、Rails のリポジトリに含まれている次の Ruby スクリプトが役に立ちます。Rails のバグ報告テンプレートだそうです。
active_record_gem.rb
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
# Activate the gem you are reporting the issue against.
gem "activerecord", "6.0.0"
gem "sqlite3"
end
require "active_record"
require "minitest/autorun"
require "logger"
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :posts, force: true do |t|
end
create_table :comments, force: true do |t|
t.integer :post_id
end
end
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
end
class BugTest < Minitest::Test
def test_association_stuff
post = Post.create!
post.comments << Comment.create!
assert_equal 1, post.comments.count
assert_equal 1, Comment.count
assert_equal post.id, Comment.first.post.id
end
end
解説
このスクリプトは次のことを行っています。
-
bundler/inline を使って Ruby スクリプト上で bundle install を行っている。
-
※ 引数を渡さない場合、bundle install の出力は画面に出ませんがインストールはされていました。gemfile
メソッドの第 1 引数にtrue
を渡すことで、まだインストールしていない Gem をインストールする。gemfile(true, quiet: true)
の場合と違いが分かっていません - (Bundler のバージョンが 2.1.0 以上の場合)
gemfile
メソッドの第 2 引数にquiet: true
を渡すと bundle install 時のログ出力を抑制できる。 -
BUNDLE_PATH
は無視する。つまり Gem は必ずグローバルにインストールされる。
-
-
ActiveRecord::Base.establish_connection の database オプションに
:memory:
を渡すことで、SQLite のデータベースをメモリ上に作成している。 - ActiveRecord::Schema.define を使うことで、スクリプト内でテーブルを定義、作成している。
- スクリプト内でモデルを定義している。
- Minitest::Test で単体テストを実行している。
いろんなテクニックがシンプルに詰まっていて、いいスクリプトだなと思いました
参考
- Bundler
-
bundler/inline should ignore BUNDLE_PATH and install gems to GEM_HOME by robuye · Pull Request #7154 · bundler/bundler
- bundler/inline での
BUNDLE_PATH
の扱いについて
- bundler/inline での
-
bundler/inline should ignore BUNDLE_PATH and install gems to GEM_HOME by robuye · Pull Request #7154 · bundler/bundler
- SQLite
-
In-Memory Databases
- インメモリのデータベースについて
-
In-Memory Databases