27
11

More than 3 years have passed since last update.

Rails のバグ報告テンプレートがすごい!

Last updated at Posted at 2019-12-17

この記事は

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 を行っている。
    • gemfile メソッドの第 1 引数に true を渡すことで、まだインストールしていない Gem をインストールする。 ※ 引数を渡さない場合、bundle install の出力は画面に出ませんがインストールはされていました。gemfile(true, quiet: true) の場合と違いが分かっていません :sob:
    • (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 で単体テストを実行している。

いろんなテクニックがシンプルに詰まっていて、いいスクリプトだなと思いました :relaxed:

参考

27
11
3

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
27
11