Help us understand the problem. What is going on with this article?

RailsのActiveRecordなどを単体で動かしてpry-byebugでデバッグする

More than 1 year has passed since last update.

Railsのソースコード読んでても黒魔術がいっぱいで、どうやって動いてるのかよく分からんです。

rails newで素のサンプルアプリケーションを作って、 pry-byebug などのデバッカを差し込んでもよいんですけど、railsのバグ報告に使われてるissueテンプレート使うと1ファイルで書けるし、rubyはdockerで実行しちゃえばクリーンな環境でできそう。

元ネタは以下です。

https://github.com/rails/rails/blob/646dd8c51fc438bf935d4192ba0479e439c1ec54/guides/bug_report_templates/active_record_gem.rb

pry-byebugの設定を追加で差し込んでおきます。

test.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.rc2"
  gem "sqlite3"
  gem 'pry-byebug'
end

require "active_record"
require "minitest/autorun"
require "logger"
require 'pry'

if defined?(PryByebug)
  Pry.commands.alias_command 'c', 'continue'
  Pry.commands.alias_command 's', 'step'
  Pry.commands.alias_command 'n', 'next'
  Pry.commands.alias_command 'f', 'finish'
end

binding.pry

# 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

$ docker run -it --rm -v $(pwd):/tmp/work ruby:2.6.3 /bin/bash
root@27dd893231b5:/# ruby /tmp/work/test.rb

From: /tmp/work/test.rb @ line 31 :

    26: end
    27:
    28: binding.pry
    29:
    30: # This connection will do for database-independent bug reports.
 => 31: ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
    32: ActiveRecord::Base.logger = Logger.new(STDOUT)
    33:
    34: ActiveRecord::Schema.define do
    35:   create_table :posts, force: true do |t|
    36:   end

あとはご自由に。

crowdworks
21世紀の新しいワークスタイルを提供する日本最大級のクラウドソーシング「クラウドワークス」のエンジニアチームです!
https://crowdworks.co.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away