Last active
August 29, 2015 14:10
-
-
Save jturkel/12de74334c4d69216d5f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| unless File.exist?('Gemfile') | |
| File.write('Gemfile', <<-GEMFILE) | |
| source 'https://rubygems.org' | |
| gem 'rails', github: 'rails/rails' | |
| gem 'arel', github: 'rails/arel' | |
| gem 'sqlite3' | |
| GEMFILE | |
| system 'bundle' | |
| end | |
| require 'bundler' | |
| Bundler.setup(:default) | |
| require 'active_record' | |
| require 'minitest/autorun' | |
| require 'logger' | |
| # Ensure backward compatibility with Minitest 4 | |
| Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test) | |
| ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:') | |
| ActiveRecord::Base.logger = Logger.new(STDOUT) | |
| # Schema | |
| ActiveRecord::Schema.define do | |
| ActiveRecord::Base.connection.create_table(:articles) | |
| ActiveRecord::Base.connection.create_table(:by_lines) do |t| | |
| t.integer :article_id | |
| t.integer :author_id | |
| t.integer :position | |
| end | |
| ActiveRecord::Base.connection.create_table(:authors) | |
| end | |
| # Models | |
| class Article < ActiveRecord::Base | |
| has_many :by_lines, -> { order(:position) } | |
| has_many :authors, through: :by_lines | |
| end | |
| class ByLine < ActiveRecord::Base | |
| belongs_to :author | |
| belongs_to :article | |
| end | |
| class Author < ActiveRecord::Base | |
| end | |
| class BugTest < Minitest::Test | |
| def setup | |
| Article.delete_all | |
| ByLine.delete_all | |
| Author.delete_all | |
| @article1 = Article.create! | |
| @article2 = Article.create! | |
| @author1 = Author.create! | |
| @author2 = Author.create! | |
| @article1.by_lines.create!(author: @author1, position: 1) | |
| @article1.by_lines.create!(author: @author2, position: 2) | |
| @article2.by_lines.create!(author: @author2, position: 1) | |
| @article2.by_lines.create!(author: @author1, position: 2) | |
| end | |
| # Just make sure it works as expected with lazy loading | |
| def test_lazy_loading | |
| @article1.reload | |
| @article2.reload | |
| assert_equal([@author1, @author2], @article1.authors) | |
| assert_equal([@author2, @author1], @article2.authors) | |
| end | |
| def test_eager_load | |
| loaded_article1 = Article.where(id: @article1.id).includes(:authors).first! | |
| loaded_article2 = Article.where(id: @article2.id).includes(:authors).first! | |
| assert_equal([@author1, @author2], loaded_article1.authors) | |
| assert_equal([@author2, @author1], loaded_article2.authors) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment