Skip to content

Instantly share code, notes, and snippets.

@BlakeWilliams
Created March 2, 2025 16:00
Show Gist options
  • Save BlakeWilliams/5707a9b4c6a00757d207b1d661dc9039 to your computer and use it in GitHub Desktop.
Save BlakeWilliams/5707a9b4c6a00757d207b1d661dc9039 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
gem "rails"
# If you want to test against edge Rails replace the previous line with this:
# gem "rails", github: "rails/rails", branch: "main"
gem "sqlite3"
end
require "action_controller/railtie"
require "active_record/railtie"
require "active_job/railtie"
require "minitest/autorun"
# Fake middleware that makes and _does not_ correctly attribute queries
class QueryMiddleware
def initialize(app)
@app = app
end
def call(env)
Post.where(id: 100).first
res = @app.call(env)
Post.where(id: 101).first
res
end
end
# This connection will do for database-independent bug reports.
ENV["DATABASE_URL"] = "sqlite3::memory:"
class TestApp < Rails::Application
config.load_defaults Rails::VERSION::STRING.to_f
config.root = __dir__
config.hosts << "example.org"
config.eager_load = false
config.logger = Logger.new($stdout)
config.secret_key_base = "secret_key_base"
config.active_record.encryption.primary_key = "primary_key"
config.active_record.encryption.deterministic_key = "deterministic_key"
config.active_record.encryption.key_derivation_salt = "key_derivation_salt"
config.middleware.use QueryMiddleware
config.active_record.query_log_tags_enabled = true
# taken directly from the docs
config.active_record.query_log_tags =[ :application, :controller, :action, :job]
end
Rails.application.initialize!
Rails.application.routes.draw do
get "/", to: "test#index"
end
ActiveRecord::Schema.define do
create_table :posts, force: true do |t|
end
end
class Post < ActiveRecord::Base
end
class OuterJob < ActiveJob::Base
def perform
Post.first
InnerJob.perform_now
Post.second
end
end
class InnerJob < ActiveJob::Base
def perform
puts "Hello world"
end
end
class TestController < ActionController::Base
include Rails.application.routes.url_helpers
def index
Post.third
InnerJob.perform_now
render plain: "Home"
Post.fourth
end
end
class BugTest < ActiveSupport::TestCase
include Rack::Test::Methods
def test_controller_query_association
queries = []
ActiveSupport::Notifications.subscribe("sql.active_record") do |name, start, finish, id, payload|
queries << payload[:sql]
Rails.logger.info "[SQL] #{payload[:sql]}" if ENV["DEBUG_QUERIES"] == 1
end
get "/"
assert last_response.ok?
assert_equal last_response.body, "Home"
refute queries.any? { |query| query.match?(/InnerJob/) }
end
private
def app
Rails.application
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment