LoginSignup
2
0

More than 3 years have passed since last update.

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

Last updated at Posted at 2019-08-08

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

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

元ネタは以下です。

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

あとはご自由に。

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