Skip to content

Instantly share code, notes, and snippets.

@senny
Created September 5, 2013 17:24
Show Gist options
  • Save senny/6453323 to your computer and use it in GitHub Desktop.
Save senny/6453323 to your computer and use it in GitHub Desktop.
require 'bundler'
Bundler.setup(:default)
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:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :posts do |t|
end
create_table :comments 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_last
post = Post.create!
post.comments << Comment.create!
post.comments << Comment.create!
post.comments << third = Comment.create!
assert_equal third, post.comments.last
end
end
@senny
Copy link
Author

senny commented Sep 5, 2013

This executes:

D, [2013-09-05T19:22:41.088416 #53973] DEBUG -- :   Comment Load (0.2ms)  SELECT  "comments".* FROM "comments"  WHERE "comments"."post_id" = ?  ORDER BY "comments"."id" DESC LIMIT 1  [["post_id", 1]]

@mbhnyc
Copy link

mbhnyc commented Sep 5, 2013

Hmmm having trouble getting this to run — can't locate MiniTest, precisely:

/Users/mhensrud/.rvm/gems/ruby-2.0.0-p0/gems/minitest-4.7.5/lib/minitest/unit.rb:19:in `const_missing': uninitialized constant MiniTest::Test (NameError)

So here's a little test out of my own suite that exhibits the issue, note this is running rails 3.2.14.

  it "should return last item correctly" do
    user = FactoryGirl.create :user
    session = FactoryGirl.create :session, user: user
    take_1 = FactoryGirl.create :take, session: session
    take_2 = FactoryGirl.create :take, session: session
    take_3 = FactoryGirl.create :take, session: session
    assert_equal take_3.id, session.takes.last.id
  end

This fails with:

  1) Failure:
Take#test_0001_should return last item correctly [/Users/mhensrud/Projects/Soundstreak/Sources/api/test/models/take_test.rb:16]:
<536> expected but was
<534>

And the SQL executed is: Take Load (0.3ms) SELECT "takes".* FROM "takes" WHERE "takes"."session_id" = 631

(Adding order("created_at") before .last gets it passing)

How should I proceed with this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment