Skip to content

Instantly share code, notes, and snippets.

@darinwilson
Last active December 19, 2024 22:31
Show Gist options
  • Save darinwilson/5fc528dc91d65270ad594cd8e761f8ab to your computer and use it in GitHub Desktop.
Save darinwilson/5fc528dc91d65270ad594cd8e761f8ab to your computer and use it in GitHub Desktop.
A single file that can run minitest within a full Rails environment - good for reproducing simple bugs
# frozen_string_literal: true
#
# to run this file:
# - bundle install
# - ruby one_file_rails_test.rb
#
# original source: https://discuss.rubyonrails.org/t/is-it-ever-ok-to-validate-the-presence-of-a-primary-key-of-a-belongs-to-association/84904
#
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
gem "rails"
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:")
# uncomment this if you want logs visible in stdout
# 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 TestCommentCreation < Minitest::Test
def test_create_post_and_comment_together
post = Post.new
comment = post.comments.build
post.save!
assert_equal Post.last, comment.reload.post
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment