From ce3ea558ab509624a1c8d8499408f52ebb4bbe2b Mon Sep 17 00:00:00 2001 From: Marcin Raczkowski Date: Sat, 28 Aug 2010 18:47:39 +0200 Subject: IdentityMap - Tests for IM --- .../test/cases/associations/join_model_test.rb | 2 +- activerecord/test/cases/identity_map_test.rb | 198 +++++++++++++++++++++ activerecord/test/cases/locking_test.rb | 13 ++ activerecord/test/cases/relations_test.rb | 6 + activerecord/test/fixtures/subscribers.yml | 4 + 5 files changed, 222 insertions(+), 1 deletion(-) create mode 100644 activerecord/test/cases/identity_map_test.rb (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb index 96edcfbb35..21f61594d7 100644 --- a/activerecord/test/cases/associations/join_model_test.rb +++ b/activerecord/test/cases/associations/join_model_test.rb @@ -104,7 +104,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase def test_polymorphic_has_many_going_through_join_model_with_custom_select_and_joins assert_equal tags(:general), tag = posts(:welcome).tags.add_joins_and_select.first - tag.author_id + assert_nothing_raised(NoMethodError) { tag.author_id } end def test_polymorphic_has_many_going_through_join_model_with_custom_foreign_key diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb new file mode 100644 index 0000000000..915f3abd26 --- /dev/null +++ b/activerecord/test/cases/identity_map_test.rb @@ -0,0 +1,198 @@ +require "cases/helper" +require 'models/developer' +require 'models/project' +require 'models/company' +require 'models/topic' +require 'models/reply' +require 'models/computer' +require 'models/customer' +require 'models/order' +require 'models/post' +require 'models/author' +require 'models/tag' +require 'models/tagging' +require 'models/comment' +require 'models/sponsor' +require 'models/member' +require 'models/essay' +require 'models/subscriber' + +class IdentityMapTest < ActiveRecord::TestCase + fixtures :accounts, :companies, :developers, :projects, :topics, + :developers_projects, :computers, :authors, :author_addresses, + :posts, :tags, :taggings, :comments, :subscribers + + def test_find_id + assert_same( + Client.find(3), + Client.find(3) + ) + end + + def test_find_pkey + assert_same( + Subscriber.find('swistak'), + Subscriber.find('swistak') + ) + end + + def test_find_by_id + assert_same( + Client.find_by_id(3), + Client.find_by_id(3) + ) + end + + def test_find_by_pkey + assert_same( + Subscriber.find_by_nick('swistak'), + Subscriber.find_by_nick('swistak') + ) + end + + def test_find_first_id + assert_same( + Client.find(:first, :conditions => {:id => 1}), + Client.find(:first, :conditions => {:id => 1}) + ) + end + + def test_find_first_pkey + assert_same( + Subscriber.find(:first, :conditions => {:nick => 'swistak'}), + Subscriber.find(:first, :conditions => {:nick => 'swistak'}) + ) + end + + def test_creation + t1 = Topic.create("title" => "t1") + t2 = Topic.find(t1.id) + assert_same(t1, t2) + end + + def test_updating_of_pkey + s = Subscriber.find_by_nick('swistak') + assert s.update_attribute(:nick, 'swistakTheJester') + assert_equal('swistakTheJester', s.nick) + + assert stj = Subscriber.find_by_nick('swistakTheJester') + assert_same(s, stj) + end + + def test_changing_associations + t1 = Topic.create("title" => "t1") + t2 = Topic.create("title" => "t2") + r1 = Reply.new("title" => "r1", "content" => "r1") + + r1.topic = t1 + assert r1.save + + assert_same(t1.replies.first, r1) + + r1.topic = t2 + assert r1.save + + assert_same(t2.replies.first, r1) + assert_equal(0, t1.replies.size) + end + + def test_im_with_polymorphic_has_many_going_through_join_model_with_custom_select_and_joins + tag = posts(:welcome).tags.first + tag_with_joins_and_select = posts(:welcome).tags.add_joins_and_select.first + assert_same(tag, tag_with_joins_and_select) + assert_nothing_raised(NoMethodError, "Joins/select was not loaded") { tag.author_id } + end + + def test_find_with_preloaded_associations + assert_queries(2) do + posts = Post.preload(:comments) + assert posts.first.comments.first + end + + # With IM we'll retrieve post object from previous query, it'll have comments + # already preloaded from first call + assert_queries(1) do + posts = Post.preload(:comments).to_a + assert posts.first.comments.first + end + + assert_queries(2) do + posts = Post.preload(:author) + assert posts.first.author + end + + # With IM we'll retrieve post object from previous query, it'll have comments + # already preloaded from first call + assert_queries(1) do + posts = Post.preload(:author).to_a + assert posts.first.author + end + + assert_queries(1) do + posts = Post.preload(:author, :comments).to_a + assert posts.first.author + assert posts.first.comments.first + end + end + + def test_find_with_included_associations + assert_queries(2) do + posts = Post.includes(:comments) + assert posts.first.comments.first + end + + assert_queries(1) do + posts = Post.scoped.includes(:comments) + assert posts.first.comments.first + end + + assert_queries(2) do + posts = Post.includes(:author) + assert posts.first.author + end + + assert_queries(1) do + posts = Post.includes(:author, :comments).to_a + assert posts.first.author + assert posts.first.comments.first + end + end + + def test_eager_loading_with_conditions_on_joined_table_preloads + posts = assert_queries(2) do + Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => [:comments], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id') + end + assert_equal [posts(:welcome)], posts + assert_equal authors(:david), assert_no_queries { posts[0].author} + + posts = assert_queries(1) do + Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => [:comments], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id') + end + assert_equal [posts(:welcome)], posts + assert_equal authors(:david), assert_no_queries { posts[0].author} + + posts = assert_queries(1) do + Post.find(:all, :include => :author, :joins => {:taggings => :tag}, :conditions => "tags.name = 'General'", :order => 'posts.id') + end + assert_equal posts(:welcome, :thinking), posts + + posts = assert_queries(2) do + Post.find(:all, :include => :author, :joins => {:taggings => {:tag => :taggings}}, :conditions => "taggings_tags.super_tag_id=2", :order => 'posts.id') + end + assert_equal posts(:welcome, :thinking), posts + end + + def test_eager_loading_with_conditions_on_string_joined_table_preloads + posts = assert_queries(2) do + Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => "INNER JOIN comments on comments.post_id = posts.id", :conditions => "comments.body like 'Thank you%'", :order => 'posts.id') + end + assert_equal [posts(:welcome)], posts + assert_equal authors(:david), assert_no_queries { posts[0].author} + + posts = assert_queries(1) do + Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => ["INNER JOIN comments on comments.post_id = posts.id"], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id') + end + assert_equal [posts(:welcome)], posts + assert_equal authors(:david), assert_no_queries { posts[0].author} + end +end diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb index 4ddcdc010b..5ceb19e7c8 100644 --- a/activerecord/test/cases/locking_test.rb +++ b/activerecord/test/cases/locking_test.rb @@ -15,6 +15,11 @@ class ReadonlyFirstNamePerson < Person attr_readonly :first_name end +# Becouse of introduction of IdentityMap optimistic locking should only be needed +# in multithreaded applications, or when more then one software operates on database. +# +# I'm using ActiveRecord::IdentityMap.without to prevent Identity map from +# using one record here. class OptimisticLockingTest < ActiveRecord::TestCase fixtures :people, :legacy_things, :references @@ -23,6 +28,10 @@ class OptimisticLockingTest < ActiveRecord::TestCase # of a test (see test_increment_counter_*). self.use_transactional_fixtures = false + def setup + ActiveRecord::IdentityMap.enabled = false + end + def test_lock_existing p1 = Person.find(1) p2 = Person.find(1) @@ -215,6 +224,10 @@ class OptimisticLockingTest < ActiveRecord::TestCase end end + def teardown + ActiveRecord::IdentityMap.enabled = true + end + private def add_counter_column_to(model, col='test_count') diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 535bcd4396..eb268017f8 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -263,6 +263,7 @@ class RelationTest < ActiveRecord::TestCase end def test_find_with_preloaded_associations + ActiveRecord::IdentityMap.without do assert_queries(2) do posts = Post.preload(:comments) assert posts.first.comments.first @@ -288,9 +289,11 @@ class RelationTest < ActiveRecord::TestCase assert posts.first.author assert posts.first.comments.first end + end end def test_find_with_included_associations + ActiveRecord::IdentityMap.without do assert_queries(2) do posts = Post.includes(:comments) assert posts.first.comments.first @@ -311,6 +314,7 @@ class RelationTest < ActiveRecord::TestCase assert posts.first.author assert posts.first.comments.first end + end end def test_default_scope_with_conditions_string @@ -552,9 +556,11 @@ class RelationTest < ActiveRecord::TestCase end def test_relation_merging_with_preload + ActiveRecord::IdentityMap.without do [Post.scoped & Post.preload(:author), Post.preload(:author) & Post.scoped].each do |posts| assert_queries(2) { assert posts.first.author } end + end end def test_relation_merging_with_joins diff --git a/activerecord/test/fixtures/subscribers.yml b/activerecord/test/fixtures/subscribers.yml index 9ffb4a156f..c6a8c2fa24 100644 --- a/activerecord/test/fixtures/subscribers.yml +++ b/activerecord/test/fixtures/subscribers.yml @@ -5,3 +5,7 @@ first: second: nick: webster132 name: David Heinemeier Hansson + +thrid: + nick: swistak + name: Marcin Raczkowski \ No newline at end of file -- cgit v1.2.3 From ce66bfdc54e3c1a4a726ebbdd3207f327d4297cf Mon Sep 17 00:00:00 2001 From: Marcin Raczkowski Date: Sat, 28 Aug 2010 18:57:50 +0200 Subject: IdentityMap - misc fixes - Added IdentityMap to be included into AR::Base - Fixed bug with Mysql namespace missing when running tests only for sqlite - Added sqlite as default connection --- activerecord/test/cases/adapters/mysql/connection_test.rb | 2 +- activerecord/test/cases/helper.rb | 9 ++++++++- 2 files changed, 9 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/adapters/mysql/connection_test.rb b/activerecord/test/cases/adapters/mysql/connection_test.rb index 62ffde558f..eb3f8143e7 100644 --- a/activerecord/test/cases/adapters/mysql/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql/connection_test.rb @@ -102,7 +102,7 @@ class MysqlConnectionTest < ActiveRecord::TestCase end # Test that MySQL allows multiple results for stored procedures - if Mysql.const_defined?(:CLIENT_MULTI_RESULTS) + if defined?(Mysql) && Mysql.const_defined?(:CLIENT_MULTI_RESULTS) def test_multi_results rows = ActiveRecord::Base.connection.select_rows('CALL ten();') assert_equal 10, rows[0][0].to_i, "ten() did not return 10 as expected: #{rows.inspect}" diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 52f26b71f5..d80e2734ce 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -11,7 +11,14 @@ require 'mocha' require 'active_record' require 'active_support/dependencies' -require 'connection' +begin + require 'connection' +rescue LoadError + # If we cannot load connection we assume that driver was not loaded for this test case, so we load sqlite3 as default one. + # This allows for running separate test cases by simply running test file. + connection_type = defined?(JRUBY_VERSION) ? 'jdbc' : 'native' + require "test/connections/#{connection_type}_sqlite3/connection" +end begin require 'ruby-debug' -- cgit v1.2.3 From ccb335da1f293dc745be0171ce3d95e50223d934 Mon Sep 17 00:00:00 2001 From: Marcin Raczkowski Date: Sun, 29 Aug 2010 12:04:43 +0200 Subject: IdentityMap - Adjustments to test cases --- .../associations/belongs_to_associations_test.rb | 20 +++++++------- .../eager_load_includes_full_sti_class_test.rb | 2 ++ activerecord/test/cases/associations/eager_test.rb | 8 ++++-- .../test/cases/autosave_association_test.rb | 7 ++++- activerecord/test/cases/identity_map_test.rb | 32 ++++++++++++++++------ activerecord/test/cases/nested_attributes_test.rb | 5 ++++ activerecord/test/cases/readonly_test.rb | 10 +++++++ 7 files changed, 62 insertions(+), 22 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index 1b0c00bd5a..f24109dcca 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -227,23 +227,23 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase end assert r1.save - assert_equal 0, Topic.find(t1.id).replies.size - assert_equal 1, Topic.find(t2.id).replies.size + assert_equal 0, t1.reload.replies.size + assert_equal 1, t2.reload.replies.size r1.topic = nil - assert_equal 0, Topic.find(t1.id).replies.size - assert_equal 0, Topic.find(t2.id).replies.size + assert_equal 0, t1.reload.replies.size + assert_equal 0, t2.reload.replies.size r1.topic = t1 - assert_equal 1, Topic.find(t1.id).replies.size - assert_equal 0, Topic.find(t2.id).replies.size + assert_equal 1, t1.reload.replies.size + assert_equal 0, t2.reload.replies.size r1.destroy - assert_equal 0, Topic.find(t1.id).replies.size - assert_equal 0, Topic.find(t2.id).replies.size + assert_equal 0, t1.reload.replies.size + assert_equal 0, t2.reload.replies.size end def test_belongs_to_reassign_with_namespaced_models_and_counters @@ -259,8 +259,8 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase r1.topic = Web::Topic.find(t2.id) assert r1.save - assert_equal 0, Web::Topic.find(t1.id).replies.size - assert_equal 1, Web::Topic.find(t2.id).replies.size + assert_equal 0, t1.reload.replies.size + assert_equal 1, t2.reload.replies.size end def test_belongs_to_counter_after_save diff --git a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb index fb59f63f91..fae4029bbc 100644 --- a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb +++ b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb @@ -27,6 +27,8 @@ class EagerLoadIncludeFullStiClassNamesTest < ActiveRecord::TestCase post = Namespaced::Post.find_by_title( 'Great stuff', :include => :tagging ) assert_nil post.tagging + ActiveRecord::IdentityMap.clear # we need to clear IM to reload post. + ActiveRecord::Base.store_full_sti_class = true post = Namespaced::Post.find_by_title( 'Great stuff', :include => :tagging ) assert_instance_of Tagging, post.tagging diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index c00b8a1cde..1782309b3e 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -170,6 +170,7 @@ class EagerAssociationTest < ActiveRecord::TestCase author = authors(:david) post = author.post_about_thinking_with_last_comment last_comment = post.last_comment + ActiveRecord::IdentityMap.clear # We need to clear cache to force reload in next block author = assert_queries(3) { Author.find(author.id, :include => {:post_about_thinking_with_last_comment => :last_comment})} # find the author, then find the posts, then find the comments assert_no_queries do assert_equal post, author.post_about_thinking_with_last_comment @@ -181,6 +182,7 @@ class EagerAssociationTest < ActiveRecord::TestCase post = posts(:welcome) author = post.author author_address = author.author_address + ActiveRecord::IdentityMap.clear # We need to clear cache to force reload in next block post = assert_queries(3) { Post.find(post.id, :include => {:author_with_address => :author_address}) } # find the post, then find the author, then find the address assert_no_queries do assert_equal author, post.author_with_address @@ -783,6 +785,7 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_eager_loading_with_conditions_on_joined_table_preloads + ActiveRecord::IdentityMap.without do # IM caches records, so we need to disable it to test this functionality. posts = assert_queries(2) do Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => [:comments], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id') end @@ -804,10 +807,11 @@ class EagerAssociationTest < ActiveRecord::TestCase Post.find(:all, :include => :author, :joins => {:taggings => {:tag => :taggings}}, :conditions => "taggings_tags.super_tag_id=2", :order => 'posts.id') end assert_equal posts(:welcome, :thinking), posts - + end end def test_eager_loading_with_conditions_on_string_joined_table_preloads + ActiveRecord::IdentityMap.without do # IM caches records, so we need to disable it to test this functionality. posts = assert_queries(2) do Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => "INNER JOIN comments on comments.post_id = posts.id", :conditions => "comments.body like 'Thank you%'", :order => 'posts.id') end @@ -819,7 +823,7 @@ class EagerAssociationTest < ActiveRecord::TestCase end assert_equal [posts(:welcome)], posts assert_equal authors(:david), assert_no_queries { posts[0].author} - + end end def test_eager_loading_with_select_on_joined_table_preloads diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index b13cb2d7a2..59fc13fe51 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -578,7 +578,7 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase @pirate.ship.mark_for_destruction assert !@pirate.reload.marked_for_destruction? - assert !@pirate.ship.marked_for_destruction? + assert !@pirate.ship.target.reload.marked_for_destruction? end # has_one @@ -1194,6 +1194,7 @@ class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::Tes self.use_transactional_fixtures = false def setup + ActiveRecord::IdentityMap.enabled = false # This tests use trick with double association, IM prevents that, so we disable it. @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") @pirate.create_ship(:name => 'titanic') end @@ -1209,6 +1210,10 @@ class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::Tes @pirate.non_validated_ship.name = '' assert @pirate.valid? end + + def teardown + ActiveRecord::IdentityMap.enabled = true + end end class TestAutosaveAssociationValidationsOnABelongsToAssociation < ActiveRecord::TestCase diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index 915f3abd26..bc0ceae605 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -70,14 +70,22 @@ class IdentityMapTest < ActiveRecord::TestCase assert_same(t1, t2) end - def test_updating_of_pkey - s = Subscriber.find_by_nick('swistak') - assert s.update_attribute(:nick, 'swistakTheJester') - assert_equal('swistakTheJester', s.nick) - - assert stj = Subscriber.find_by_nick('swistakTheJester') - assert_same(s, stj) - end +# Currently AR is not allowing changing primary key (see Persistence#update) +# So we ignore it. If this changes, this test needs to be uncommented. +# def test_updating_of_pkey +# assert client = Client.find(3), +# client.update_attribute(:id, 666) +# +# assert Client.find(666) +# assert_same(client, Client.find(666)) +# +# s = Subscriber.find_by_nick('swistak') +# assert s.update_attribute(:nick, 'swistakTheJester') +# assert_equal('swistakTheJester', s.nick) +# +# assert stj = Subscriber.find_by_nick('swistakTheJester') +# assert_same(s, stj) +# end def test_changing_associations t1 = Topic.create("title" => "t1") @@ -176,7 +184,7 @@ class IdentityMapTest < ActiveRecord::TestCase end assert_equal posts(:welcome, :thinking), posts - posts = assert_queries(2) do + posts = assert_queries(1) do Post.find(:all, :include => :author, :joins => {:taggings => {:tag => :taggings}}, :conditions => "taggings_tags.super_tag_id=2", :order => 'posts.id') end assert_equal posts(:welcome, :thinking), posts @@ -195,4 +203,10 @@ class IdentityMapTest < ActiveRecord::TestCase assert_equal [posts(:welcome)], posts assert_equal authors(:david), assert_no_queries { posts[0].author} end + + # Second search should not change read only status for collection + def test_find_with_joins_option_implies_readonly + Developer.joins(', projects').each { |d| assert d.readonly? } + Developer.joins(', projects').readonly(false).each { |d| assert d.readonly? } + end end diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index 92af53d56f..e4697ae4a4 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -551,9 +551,14 @@ module NestedAttributesOnACollectionAssociationTests assert_equal 'Grace OMalley', @child_1.reload.name end + def test_should_not_overwrite_unsaved_updates_when_loading_association @pirate.reload +# p(@pirate.send(@association_name)) @pirate.send(association_setter, [{ :id => @child_1.id, :name => 'Grace OMalley' }]) +# p(@pirate.send(@association_name)) +# p([@pirate.send(@association_name).detect { |r| r.id == @child_1.id }, @child_1.id]) +# puts assert_equal 'Grace OMalley', @pirate.send(@association_name).send(:load_target).find { |r| r.id == @child_1.id }.name end diff --git a/activerecord/test/cases/readonly_test.rb b/activerecord/test/cases/readonly_test.rb index 98011f40a4..448c8f8796 100644 --- a/activerecord/test/cases/readonly_test.rb +++ b/activerecord/test/cases/readonly_test.rb @@ -40,6 +40,10 @@ class ReadOnlyTest < ActiveRecord::TestCase def test_find_with_joins_option_implies_readonly + # We disable IM, becouse we want to check default settings here + # adding readonly(false) does not update readonly status with IM + # (see corresponding test in IM) + ActiveRecord::IdentityMap.without do # Blank joins don't count. Developer.joins(' ').each { |d| assert !d.readonly? } Developer.joins(' ').readonly(false).each { |d| assert !d.readonly? } @@ -47,6 +51,7 @@ class ReadOnlyTest < ActiveRecord::TestCase # Others do. Developer.joins(', projects').each { |d| assert d.readonly? } Developer.joins(', projects').readonly(false).each { |d| assert !d.readonly? } + end end @@ -72,6 +77,10 @@ class ReadOnlyTest < ActiveRecord::TestCase end def test_readonly_scoping + # We disable IM, becouse we want to check default settings here + # adding readonly(false) does not update readonly status with IM + # (see corresponding test in IM) + ActiveRecord::IdentityMap.without do Post.send(:with_scope, :find => { :conditions => '1=1' }) do assert !Post.find(1).readonly? assert Post.readonly(true).find(1).readonly? @@ -99,6 +108,7 @@ class ReadOnlyTest < ActiveRecord::TestCase assert Post.readonly.find(1).readonly? assert !Post.readonly(false).find(1).readonly? end + end end def test_association_collection_method_missing_scoping_not_readonly -- cgit v1.2.3 From eebf33a2347bd4717b6ce966c2b7def4d573ec51 Mon Sep 17 00:00:00 2001 From: Marcin Raczkowski Date: Mon, 6 Sep 2010 03:30:06 +0200 Subject: IdentityMap - Fixes problem with dirty attributes --- activerecord/test/cases/identity_map_test.rb | 32 +++++++++++++++++++++++ activerecord/test/cases/nested_attributes_test.rb | 4 --- 2 files changed, 32 insertions(+), 4 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index bc0ceae605..d157443b7b 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -16,6 +16,9 @@ require 'models/sponsor' require 'models/member' require 'models/essay' require 'models/subscriber' +require "models/pirate" +require "models/bird" +require "models/parrot" class IdentityMapTest < ActiveRecord::TestCase fixtures :accounts, :companies, :developers, :projects, :topics, @@ -70,6 +73,35 @@ class IdentityMapTest < ActiveRecord::TestCase assert_same(t1, t2) end + def test_loading_new_instance_should_not_update_dirty_attributes + swistak = Subscriber.find(:first, :conditions => {:nick => 'swistak'}) + swistak.name = "Swistak Sreberkowiec" + assert_equal(["name"], swistak.changed) + + s = Subscriber.find('swistak') + + assert swistak.name_changed? + assert_equal("Swistak Sreberkowiec", swistak.name) + end + + def test_loading_new_instance_should_remove_dirt + #assert_equal({'name' => ["Marcin Raczkowski", "Swistak Sreberkowiec"]}, swistak.changes) + #assert_equal("Swistak Sreberkowiec", swistak.name) + end + + def test_has_many_associations + pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?") + pirate.birds.create!(:name => 'Posideons Killer') + pirate.birds.create!(:name => 'Killer bandita Dionne') + + posideons, killer = pirate.birds + + pirate.reload + + pirate.birds_attributes = [{ :id => posideons.id, :name => 'Grace OMalley' }] + assert_equal 'Grace OMalley', pirate.birds.send(:load_target).find { |r| r.id == posideons.id }.name + end + # Currently AR is not allowing changing primary key (see Persistence#update) # So we ignore it. If this changes, this test needs to be uncommented. # def test_updating_of_pkey diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index e4697ae4a4..20a24c38fa 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -554,11 +554,7 @@ module NestedAttributesOnACollectionAssociationTests def test_should_not_overwrite_unsaved_updates_when_loading_association @pirate.reload -# p(@pirate.send(@association_name)) @pirate.send(association_setter, [{ :id => @child_1.id, :name => 'Grace OMalley' }]) -# p(@pirate.send(@association_name)) -# p([@pirate.send(@association_name).detect { |r| r.id == @child_1.id }, @child_1.id]) -# puts assert_equal 'Grace OMalley', @pirate.send(@association_name).send(:load_target).find { |r| r.id == @child_1.id }.name end -- cgit v1.2.3 From f1913ad835abce53b5365c11c9d13975c1d8ba46 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 15 Sep 2010 10:58:59 -0300 Subject: Uncomment test and make it work. --- activerecord/test/cases/identity_map_test.rb | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index d157443b7b..df43d8c4f4 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -85,8 +85,11 @@ class IdentityMapTest < ActiveRecord::TestCase end def test_loading_new_instance_should_remove_dirt - #assert_equal({'name' => ["Marcin Raczkowski", "Swistak Sreberkowiec"]}, swistak.changes) - #assert_equal("Swistak Sreberkowiec", swistak.name) + swistak = Subscriber.find(:first, :conditions => {:nick => 'swistak'}) + swistak.name = "Swistak Sreberkowiec" + + assert_equal({'name' => ["Marcin Raczkowski", "Swistak Sreberkowiec"]}, swistak.changes) + assert_equal("Swistak Sreberkowiec", swistak.name) end def test_has_many_associations -- cgit v1.2.3 From a9edd6cf932b299e28677cb1e0af397c533caffe Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 15 Sep 2010 11:09:30 -0300 Subject: Add test to show that when IdentityMap is disabled finders returns different objects. --- activerecord/test/cases/identity_map_test.rb | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index df43d8c4f4..c51bdf5f69 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -26,10 +26,13 @@ class IdentityMapTest < ActiveRecord::TestCase :posts, :tags, :taggings, :comments, :subscribers def test_find_id - assert_same( - Client.find(3), - Client.find(3) - ) + assert_same(Client.find(3), Client.find(3)) + end + + def test_find_id_without_identity_map + IdentityMap.without do + assert_not_same(Client.find(3), Client.find(3)) + end end def test_find_pkey -- cgit v1.2.3 From e83f5a0ae97889dddfd0956081b0f4582594cda9 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 15 Sep 2010 11:18:34 -0300 Subject: Remove objects from identity map if save failed, otherwise finding again the same record will have invalid attributes. --- activerecord/test/cases/identity_map_test.rb | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index c51bdf5f69..d4be698082 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -30,7 +30,7 @@ class IdentityMapTest < ActiveRecord::TestCase end def test_find_id_without_identity_map - IdentityMap.without do + ActiveRecord::IdentityMap.without do assert_not_same(Client.find(3), Client.find(3)) end end @@ -247,4 +247,18 @@ class IdentityMapTest < ActiveRecord::TestCase Developer.joins(', projects').each { |d| assert d.readonly? } Developer.joins(', projects').readonly(false).each { |d| assert d.readonly? } end + + def test_reload_object_if_save_failed + developer = Developer.first + developer.salary = 0 + + assert !developer.save + + same_developer = Developer.first + + assert_not_same developer, same_developer + assert_not_equal 0, same_developer.salary + assert_not_equal developer.salary, same_developer.salary + end + end -- cgit v1.2.3 From f3adddb966f3c93de4992b42cf554e3ef2a3acf1 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 15 Sep 2010 11:22:24 -0300 Subject: Remove objects from identity map if save! failed, otherwise finding again the same record will have invalid attributes. --- activerecord/test/cases/identity_map_test.rb | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index d4be698082..1683bd28c3 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -261,4 +261,17 @@ class IdentityMapTest < ActiveRecord::TestCase assert_not_equal developer.salary, same_developer.salary end + def test_reload_object_if_forced_save_failed + developer = Developer.first + developer.salary = 0 + + assert_raise(ActiveRecord::RecordInvalid) { developer.save! } + + same_developer = Developer.first + + assert_not_same developer, same_developer + assert_not_equal 0, same_developer.salary + assert_not_equal developer.salary, same_developer.salary + end + end -- cgit v1.2.3 From 6b0b95f1bd92e2ef35573cb59e8a14bd3ffb3777 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 15 Sep 2010 11:30:15 -0300 Subject: Add test for update_attributes and identity map. --- activerecord/test/cases/identity_map_test.rb | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index 1683bd28c3..7deda56541 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -274,4 +274,17 @@ class IdentityMapTest < ActiveRecord::TestCase assert_not_equal developer.salary, same_developer.salary end + def test_reload_object_if_update_attributes_fails + developer = Developer.first + developer.salary = 0 + + assert !developer.update_attributes(:salary => 0) + + same_developer = Developer.first + + assert_not_same developer, same_developer + assert_not_equal 0, same_developer.salary + assert_not_equal developer.salary, same_developer.salary + end + end -- cgit v1.2.3 From 234bbe5cb0e31b786cc73e8f63e55a9ce8aecf88 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 15 Sep 2010 15:38:38 -0300 Subject: Associated objects are assigned from identity map if enabled and contains associated object. --- activerecord/test/cases/identity_map_test.rb | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index 7deda56541..e62e99361a 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -287,4 +287,22 @@ class IdentityMapTest < ActiveRecord::TestCase assert_not_equal developer.salary, same_developer.salary end + def test_owner_object_is_associated_from_identity_map + post = Post.find(1) + comment = post.comments.first + + assert_no_queries do + comment.post + end + assert_same post, comment.post + end + + def test_associated_object_are_assigned_from_identity_map + post = Post.find(1) + + post.comments.each do |comment| + assert_same post, comment.post + assert_equal post.object_id, comment.post.target.object_id + end + end end -- cgit v1.2.3 From 448420ff7d082c98a538edd47dd24490e302c5ec Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 15 Sep 2010 16:43:36 -0300 Subject: Add tests for inverse relations when using has many and identity map. --- .../test/cases/associations/identity_map_test.rb | 134 +++++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 activerecord/test/cases/associations/identity_map_test.rb (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/identity_map_test.rb b/activerecord/test/cases/associations/identity_map_test.rb new file mode 100644 index 0000000000..cfb1d4efe0 --- /dev/null +++ b/activerecord/test/cases/associations/identity_map_test.rb @@ -0,0 +1,134 @@ +require "cases/helper" +require 'models/author' +require 'models/post' + +class InverseHasManyIdentityMapTest < ActiveRecord::TestCase + fixtures :authors, :posts + + def test_parent_instance_should_be_shared_with_every_child_on_find + m = Author.first + is = m.posts + is.each do |i| + assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance" + m.name = 'Bongo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance" + i.author.name = 'Mungo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to child-owned instance" + end + end + + def test_parent_instance_should_be_shared_with_eager_loaded_children + m = Author.find(:first, :include => :posts) + is = m.posts + is.each do |i| + assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance" + m.name = 'Bongo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance" + i.author.name = 'Mungo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to child-owned instance" + end + + m = Author.find(:first, :include => :posts, :order => 'posts.id') + is = m.posts + is.each do |i| + assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance" + m.name = 'Bongo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance" + i.author.name = 'Mungo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to child-owned instance" + end + end + + def test_parent_instance_should_be_shared_with_newly_built_child + m = Author.first + i = m.posts.build(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum') + assert_not_nil i.author + assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance" + m.name = 'Bongo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance" + i.author.name = 'Mungo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to just-built-child-owned instance" + end + + def test_parent_instance_should_be_shared_with_newly_block_style_built_child + m = Author.first + i = m.posts.build {|ii| ii.title = 'Industrial Revolution Re-enactment'; ii.body = 'Lorem ipsum'} + assert_not_nil i.title, "Child attributes supplied to build via blocks should be populated" + assert_not_nil i.author + assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance" + m.name = 'Bongo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance" + i.author.name = 'Mungo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to just-built-child-owned instance" + end + + def test_parent_instance_should_be_shared_with_newly_created_child + m = Author.first + i = m.posts.create(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum') + assert_not_nil i.author + assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance" + m.name = 'Bongo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance" + i.author.name = 'Mungo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to newly-created-child-owned instance" + end + + def test_parent_instance_should_be_shared_with_newly_created_via_bang_method_child + m = Author.first + i = m.posts.create!(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum') + assert_not_nil i.author + assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance" + m.name = 'Bongo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance" + i.author.name = 'Mungo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to newly-created-child-owned instance" + end + + def test_parent_instance_should_be_shared_with_newly_block_style_created_child + m = Author.first + i = m.posts.create {|ii| ii.title = 'Industrial Revolution Re-enactment'; ii.body = 'Lorem ipsum'} + assert_not_nil i.title, "Child attributes supplied to create via blocks should be populated" + assert_not_nil i.author + assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance" + m.name = 'Bongo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance" + i.author.name = 'Mungo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to newly-created-child-owned instance" + end + + def test_parent_instance_should_be_shared_with_poked_in_child + m = Author.first + i = Post.create(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum') + m.posts << i + assert_not_nil i.author + assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance" + m.name = 'Bongo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance" + i.author.name = 'Mungo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to newly-created-child-owned instance" + end + + def test_parent_instance_should_be_shared_with_replaced_via_accessor_children + m = Author.first + i = Post.new(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum') + m.posts = [i] + assert_not_nil i.author + assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance" + m.name = 'Bongo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance" + i.author.name = 'Mungo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to replaced-child-owned instance" + end + + def test_parent_instance_should_be_shared_with_replaced_via_method_children + m = Author.first + i = Post.new(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum') + m.posts.replace([i]) + assert_not_nil i.author + assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance" + m.name = 'Bongo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to parent instance" + i.author.name = 'Mungo' + assert_equal m.name, i.author.name, "Name of man should be the same after changes to replaced-child-owned instance" + end +end -- cgit v1.2.3 From c0ad5e48f643e9721059e94ba23dab3159eebb93 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Fri, 17 Sep 2010 16:00:06 -0300 Subject: Don't use identity map if loading readonly records, this will prevent changing readonly status on already loaded records. --- activerecord/test/cases/identity_map_test.rb | 32 ++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index e62e99361a..5edbd34be2 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -242,12 +242,6 @@ class IdentityMapTest < ActiveRecord::TestCase assert_equal authors(:david), assert_no_queries { posts[0].author} end - # Second search should not change read only status for collection - def test_find_with_joins_option_implies_readonly - Developer.joins(', projects').each { |d| assert d.readonly? } - Developer.joins(', projects').readonly(false).each { |d| assert d.readonly? } - end - def test_reload_object_if_save_failed developer = Developer.first developer.salary = 0 @@ -305,4 +299,30 @@ class IdentityMapTest < ActiveRecord::TestCase assert_equal post.object_id, comment.post.target.object_id end end + + def test_find_using_identity_map_respects_readonly_when_loading_associated_object_first + author = Author.first + readonly_comment = author.readonly_comments.first + + comment = Comment.first + assert !comment.readonly? + + assert readonly_comment.readonly? + + assert_raise(ActiveRecord::ReadOnlyRecord) {readonly_comment.save} + assert comment.save + end + + def test_find_using_identity_map_respects_readonly + comment = Comment.first + assert !comment.readonly? + + author = Author.first + readonly_comment = author.readonly_comments.first + + assert readonly_comment.readonly? + + assert_raise(ActiveRecord::ReadOnlyRecord) {readonly_comment.save} + assert comment.save + end end -- cgit v1.2.3 From cd6d6fcb239f08ce039d2f70960014477f4e550b Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 21 Sep 2010 10:54:54 -0300 Subject: Change test models. --- activerecord/test/cases/identity_map_test.rb | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index 5edbd34be2..f9eef250d3 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -126,20 +126,20 @@ class IdentityMapTest < ActiveRecord::TestCase # end def test_changing_associations - t1 = Topic.create("title" => "t1") - t2 = Topic.create("title" => "t2") - r1 = Reply.new("title" => "r1", "content" => "r1") + post1 = Post.create("title" => "One post", "body" => "Posting...") + post2 = Post.create("title" => "Another post", "body" => "Posting... Again...") + comment = Comment.new("body" => "comment") - r1.topic = t1 - assert r1.save + comment.post = post1 + assert comment.save - assert_same(t1.replies.first, r1) + assert_same(post1.comments.first, comment) - r1.topic = t2 - assert r1.save + comment.post = post2 + assert comment.save - assert_same(t2.replies.first, r1) - assert_equal(0, t1.replies.size) + assert_same(post2.comments.first, comment) + assert_equal(0, post1.comments.size) end def test_im_with_polymorphic_has_many_going_through_join_model_with_custom_select_and_joins -- cgit v1.2.3 From 21483cbc6755b1a8aae5bc2285fb439c22fb5265 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 21 Sep 2010 17:46:20 -0300 Subject: Testing objects equality is what we are looking for here, no query caching. --- activerecord/test/cases/identity_map_test.rb | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index f9eef250d3..d5ef993a8c 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -205,27 +205,23 @@ class IdentityMapTest < ActiveRecord::TestCase end def test_eager_loading_with_conditions_on_joined_table_preloads - posts = assert_queries(2) do - Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => [:comments], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id') - end + posts = Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => [:comments], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id') assert_equal [posts(:welcome)], posts assert_equal authors(:david), assert_no_queries { posts[0].author} + assert_same posts.first.author.target, Author.first - posts = assert_queries(1) do - Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => [:comments], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id') - end + posts = Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => [:comments], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id') assert_equal [posts(:welcome)], posts assert_equal authors(:david), assert_no_queries { posts[0].author} + assert_same posts.first.author.target, Author.first - posts = assert_queries(1) do - Post.find(:all, :include => :author, :joins => {:taggings => :tag}, :conditions => "tags.name = 'General'", :order => 'posts.id') - end + posts = Post.find(:all, :include => :author, :joins => {:taggings => :tag}, :conditions => "tags.name = 'General'", :order => 'posts.id') assert_equal posts(:welcome, :thinking), posts + assert_same posts.first.author.target, Author.first - posts = assert_queries(1) do - Post.find(:all, :include => :author, :joins => {:taggings => {:tag => :taggings}}, :conditions => "taggings_tags.super_tag_id=2", :order => 'posts.id') - end + posts = Post.find(:all, :include => :author, :joins => {:taggings => {:tag => :taggings}}, :conditions => "taggings_tags.super_tag_id=2", :order => 'posts.id') assert_equal posts(:welcome, :thinking), posts + assert_same posts.first.author.target, Author.first end def test_eager_loading_with_conditions_on_string_joined_table_preloads -- cgit v1.2.3 From ab4238203f886ff6fb2b0060179d39770be6be1c Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 21 Sep 2010 19:32:36 -0300 Subject: Test with target object, failing on 1.9.2 when comparing object against association proxy object. --- activerecord/test/cases/associations/identity_map_test.rb | 1 + activerecord/test/cases/identity_map_test.rb | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/identity_map_test.rb b/activerecord/test/cases/associations/identity_map_test.rb index cfb1d4efe0..3d3ae0594b 100644 --- a/activerecord/test/cases/associations/identity_map_test.rb +++ b/activerecord/test/cases/associations/identity_map_test.rb @@ -112,6 +112,7 @@ class InverseHasManyIdentityMapTest < ActiveRecord::TestCase m = Author.first i = Post.new(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum') m.posts = [i] + assert_same m, i.author.target assert_not_nil i.author assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance" m.name = 'Bongo' diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index d5ef993a8c..d51de22f64 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -284,14 +284,14 @@ class IdentityMapTest < ActiveRecord::TestCase assert_no_queries do comment.post end - assert_same post, comment.post + assert_same post, comment.post.target end def test_associated_object_are_assigned_from_identity_map post = Post.find(1) post.comments.each do |comment| - assert_same post, comment.post + assert_same post, comment.post.target assert_equal post.object_id, comment.post.target.object_id end end -- cgit v1.2.3 From 6d58b274222ddd917939998761f75e3d87756a3e Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 21 Sep 2010 19:48:57 -0300 Subject: Set Identity Map disabled by default. Enable it for testing. --- activerecord/test/cases/helper.rb | 3 +++ 1 file changed, 3 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index d80e2734ce..7db55da02a 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -31,6 +31,9 @@ ActiveSupport::Deprecation.debug = true # Quote "type" if it's a reserved word for the current connection. QUOTED_TYPE = ActiveRecord::Base.connection.quote_column_name('type') +# Enable Identity Map for testing +ActiveRecord::IdentityMap.enabled = true + def current_adapter?(*types) types.any? do |type| ActiveRecord::ConnectionAdapters.const_defined?(type) && -- cgit v1.2.3 From 740450514ce86d56926d8749b1e230012b368567 Mon Sep 17 00:00:00 2001 From: Marcin Raczkowski Date: Sun, 3 Oct 2010 15:10:35 +0200 Subject: Test reorganization --- activerecord/test/cases/identity_map_test.rb | 119 +++++++++++++++++++-------- 1 file changed, 83 insertions(+), 36 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index d51de22f64..53835e3b46 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -25,6 +25,10 @@ class IdentityMapTest < ActiveRecord::TestCase :developers_projects, :computers, :authors, :author_addresses, :posts, :tags, :taggings, :comments, :subscribers + ############################################################################## + # Basic tests checking if IM is functioning properly on basic find operations# + ############################################################################## + def test_find_id assert_same(Client.find(3), Client.find(3)) end @@ -70,16 +74,45 @@ class IdentityMapTest < ActiveRecord::TestCase ) end + ############################################################################## + # Tests checking if IM is functioning properly on more advanced finds # + # and associations # + ############################################################################## + + def test_owner_object_is_associated_from_identity_map + post = Post.find(1) + comment = post.comments.first + + assert_no_queries do + comment.post + end + assert_same post, comment.post.target + end + + def test_associated_object_are_assigned_from_identity_map + post = Post.find(1) + + post.comments.each do |comment| + assert_same post, comment.post.target + assert_equal post.object_id, comment.post.target.object_id + end + end + def test_creation t1 = Topic.create("title" => "t1") t2 = Topic.find(t1.id) assert_same(t1, t2) end + ############################################################################## + # Tests checking dirty attribute behaviour with IM # + ############################################################################## + def test_loading_new_instance_should_not_update_dirty_attributes swistak = Subscriber.find(:first, :conditions => {:nick => 'swistak'}) swistak.name = "Swistak Sreberkowiec" assert_equal(["name"], swistak.changed) + assert_equal({"name" => ["Marcin Raczkowski", "Swistak Sreberkowiec"]}, swistak.changes) s = Subscriber.find('swistak') @@ -87,12 +120,31 @@ class IdentityMapTest < ActiveRecord::TestCase assert_equal("Swistak Sreberkowiec", swistak.name) end + def test_loading_new_instance_should_change_dirty_attribute original_value + swistak = Subscriber.find(:first, :conditions => {:nick => 'swistak'}) + swistak.name = "Swistak Sreberkowiec" + + Susbscriber.update_all({:name => "Raczkowski Marcin"}, {:name => "Marcin Raczkowski"}) + + s = Subscriber.find('swistak') + + assert_equal({'name' => ["Raczkowski Marcin", "Swistak Sreberkowiec"]}, swistak.changes) + assert_equal("Swistak Sreberkowiec", swistak.name) + end + def test_loading_new_instance_should_remove_dirt swistak = Subscriber.find(:first, :conditions => {:nick => 'swistak'}) swistak.name = "Swistak Sreberkowiec" - assert_equal({'name' => ["Marcin Raczkowski", "Swistak Sreberkowiec"]}, swistak.changes) + assert_equal({"name" => ["Marcin Raczkowski", "Swistak Sreberkowiec"]}, swistak.changes) + + Subscriber.update_all({:name => "Swistak Sreberkowiec"}, {:name => "Marcin Raczkowski"}) + + s = Subscriber.find('swistak') + assert_equal("Swistak Sreberkowiec", swistak.name) + assert_equal({}, swistak.changes) + assert !swistak.name_changed? end def test_has_many_associations @@ -108,23 +160,6 @@ class IdentityMapTest < ActiveRecord::TestCase assert_equal 'Grace OMalley', pirate.birds.send(:load_target).find { |r| r.id == posideons.id }.name end -# Currently AR is not allowing changing primary key (see Persistence#update) -# So we ignore it. If this changes, this test needs to be uncommented. -# def test_updating_of_pkey -# assert client = Client.find(3), -# client.update_attribute(:id, 666) -# -# assert Client.find(666) -# assert_same(client, Client.find(666)) -# -# s = Subscriber.find_by_nick('swistak') -# assert s.update_attribute(:nick, 'swistakTheJester') -# assert_equal('swistakTheJester', s.nick) -# -# assert stj = Subscriber.find_by_nick('swistakTheJester') -# assert_same(s, stj) -# end - def test_changing_associations post1 = Post.create("title" => "One post", "body" => "Posting...") post2 = Post.create("title" => "Another post", "body" => "Posting... Again...") @@ -149,6 +184,11 @@ class IdentityMapTest < ActiveRecord::TestCase assert_nothing_raised(NoMethodError, "Joins/select was not loaded") { tag.author_id } end + ############################################################################## + # Tests checking Identity Map behaviour with preloaded associations, joins, # + # includes etc. # + ############################################################################## + def test_find_with_preloaded_associations assert_queries(2) do posts = Post.preload(:comments) @@ -238,6 +278,10 @@ class IdentityMapTest < ActiveRecord::TestCase assert_equal authors(:david), assert_no_queries { posts[0].author} end + ############################################################################## + # Behaviour releated to saving failures + ############################################################################## + def test_reload_object_if_save_failed developer = Developer.first developer.salary = 0 @@ -277,24 +321,9 @@ class IdentityMapTest < ActiveRecord::TestCase assert_not_equal developer.salary, same_developer.salary end - def test_owner_object_is_associated_from_identity_map - post = Post.find(1) - comment = post.comments.first - - assert_no_queries do - comment.post - end - assert_same post, comment.post.target - end - - def test_associated_object_are_assigned_from_identity_map - post = Post.find(1) - - post.comments.each do |comment| - assert_same post, comment.post.target - assert_equal post.object_id, comment.post.target.object_id - end - end + ############################################################################## + # Behaviour of readonly, forzen, destroyed + ############################################################################## def test_find_using_identity_map_respects_readonly_when_loading_associated_object_first author = Author.first @@ -321,4 +350,22 @@ class IdentityMapTest < ActiveRecord::TestCase assert_raise(ActiveRecord::ReadOnlyRecord) {readonly_comment.save} assert comment.save end + +# Currently AR is not allowing changing primary key (see Persistence#update) +# So we ignore it. If this changes, this test needs to be uncommented. +# def test_updating_of_pkey +# assert client = Client.find(3), +# client.update_attribute(:id, 666) +# +# assert Client.find(666) +# assert_same(client, Client.find(666)) +# +# s = Subscriber.find_by_nick('swistak') +# assert s.update_attribute(:nick, 'swistakTheJester') +# assert_equal('swistakTheJester', s.nick) +# +# assert stj = Subscriber.find_by_nick('swistakTheJester') +# assert_same(s, stj) +# end + end -- cgit v1.2.3 From 003e4fb4cf7a2eabd60cceb4a1e0e857ada282f0 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 6 Oct 2010 12:09:18 -0300 Subject: Fix test name and typo. --- activerecord/test/cases/identity_map_test.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index 53835e3b46..f984c42ffb 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -120,11 +120,11 @@ class IdentityMapTest < ActiveRecord::TestCase assert_equal("Swistak Sreberkowiec", swistak.name) end - def test_loading_new_instance_should_change_dirty_attribute original_value + def test_loading_new_instance_should_change_dirty_attribute_original_value swistak = Subscriber.find(:first, :conditions => {:nick => 'swistak'}) swistak.name = "Swistak Sreberkowiec" - Susbscriber.update_all({:name => "Raczkowski Marcin"}, {:name => "Marcin Raczkowski"}) + Subscriber.update_all({:name => "Raczkowski Marcin"}, {:name => "Marcin Raczkowski"}) s = Subscriber.find('swistak') -- cgit v1.2.3 From 301dd3d5143077f95bebd434ca2ad1c80c1b5866 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Thu, 14 Oct 2010 12:58:47 -0300 Subject: Use hash[:Post][1] style identity maps for each table. --- activerecord/test/cases/identity_map_test.rb | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index f984c42ffb..1588633e1d 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -53,6 +53,13 @@ class IdentityMapTest < ActiveRecord::TestCase ) end + def test_find_by_string_and_numeric_id + assert_same( + Client.find_by_id("3"), + Client.find_by_id(3) + ) + end + def test_find_by_pkey assert_same( Subscriber.find_by_nick('swistak'), -- cgit v1.2.3 From 08c37b7ed8281bc3e3c1eca98a4859017c89157a Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Fri, 15 Oct 2010 15:44:21 -0300 Subject: Use block syntax in IdentityMap middleware. --- activerecord/test/cases/identity_map_test.rb | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index 1588633e1d..df77bc5af2 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -39,6 +39,14 @@ class IdentityMapTest < ActiveRecord::TestCase end end + def test_find_id_use_identity_map + ActiveRecord::IdentityMap.enabled = false + ActiveRecord::IdentityMap.use do + assert_same(Client.find(3), Client.find(3)) + end + ActiveRecord::IdentityMap.enabled = true + end + def test_find_pkey assert_same( Subscriber.find('swistak'), -- cgit v1.2.3 From 93daf1b80984eab80f0da13c2b42ae76b63085e3 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 20 Oct 2010 16:11:59 -0300 Subject: Revert "IdentityMap - Adjustments to test cases" This reverts commit 4db9dca55e3acc2c59f252eb83ecb83db5f4b81b. Conflicts: activerecord/test/cases/identity_map_test.rb --- .../associations/belongs_to_associations_test.rb | 20 ++++++++++---------- .../eager_load_includes_full_sti_class_test.rb | 2 -- activerecord/test/cases/associations/eager_test.rb | 8 ++------ activerecord/test/cases/autosave_association_test.rb | 7 +------ activerecord/test/cases/identity_map_test.rb | 1 + activerecord/test/cases/nested_attributes_test.rb | 1 - activerecord/test/cases/readonly_test.rb | 10 ---------- 7 files changed, 14 insertions(+), 35 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index f24109dcca..1b0c00bd5a 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -227,23 +227,23 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase end assert r1.save - assert_equal 0, t1.reload.replies.size - assert_equal 1, t2.reload.replies.size + assert_equal 0, Topic.find(t1.id).replies.size + assert_equal 1, Topic.find(t2.id).replies.size r1.topic = nil - assert_equal 0, t1.reload.replies.size - assert_equal 0, t2.reload.replies.size + assert_equal 0, Topic.find(t1.id).replies.size + assert_equal 0, Topic.find(t2.id).replies.size r1.topic = t1 - assert_equal 1, t1.reload.replies.size - assert_equal 0, t2.reload.replies.size + assert_equal 1, Topic.find(t1.id).replies.size + assert_equal 0, Topic.find(t2.id).replies.size r1.destroy - assert_equal 0, t1.reload.replies.size - assert_equal 0, t2.reload.replies.size + assert_equal 0, Topic.find(t1.id).replies.size + assert_equal 0, Topic.find(t2.id).replies.size end def test_belongs_to_reassign_with_namespaced_models_and_counters @@ -259,8 +259,8 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase r1.topic = Web::Topic.find(t2.id) assert r1.save - assert_equal 0, t1.reload.replies.size - assert_equal 1, t2.reload.replies.size + assert_equal 0, Web::Topic.find(t1.id).replies.size + assert_equal 1, Web::Topic.find(t2.id).replies.size end def test_belongs_to_counter_after_save diff --git a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb index fae4029bbc..fb59f63f91 100644 --- a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb +++ b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb @@ -27,8 +27,6 @@ class EagerLoadIncludeFullStiClassNamesTest < ActiveRecord::TestCase post = Namespaced::Post.find_by_title( 'Great stuff', :include => :tagging ) assert_nil post.tagging - ActiveRecord::IdentityMap.clear # we need to clear IM to reload post. - ActiveRecord::Base.store_full_sti_class = true post = Namespaced::Post.find_by_title( 'Great stuff', :include => :tagging ) assert_instance_of Tagging, post.tagging diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index 1782309b3e..c00b8a1cde 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -170,7 +170,6 @@ class EagerAssociationTest < ActiveRecord::TestCase author = authors(:david) post = author.post_about_thinking_with_last_comment last_comment = post.last_comment - ActiveRecord::IdentityMap.clear # We need to clear cache to force reload in next block author = assert_queries(3) { Author.find(author.id, :include => {:post_about_thinking_with_last_comment => :last_comment})} # find the author, then find the posts, then find the comments assert_no_queries do assert_equal post, author.post_about_thinking_with_last_comment @@ -182,7 +181,6 @@ class EagerAssociationTest < ActiveRecord::TestCase post = posts(:welcome) author = post.author author_address = author.author_address - ActiveRecord::IdentityMap.clear # We need to clear cache to force reload in next block post = assert_queries(3) { Post.find(post.id, :include => {:author_with_address => :author_address}) } # find the post, then find the author, then find the address assert_no_queries do assert_equal author, post.author_with_address @@ -785,7 +783,6 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_eager_loading_with_conditions_on_joined_table_preloads - ActiveRecord::IdentityMap.without do # IM caches records, so we need to disable it to test this functionality. posts = assert_queries(2) do Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => [:comments], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id') end @@ -807,11 +804,10 @@ class EagerAssociationTest < ActiveRecord::TestCase Post.find(:all, :include => :author, :joins => {:taggings => {:tag => :taggings}}, :conditions => "taggings_tags.super_tag_id=2", :order => 'posts.id') end assert_equal posts(:welcome, :thinking), posts - end + end def test_eager_loading_with_conditions_on_string_joined_table_preloads - ActiveRecord::IdentityMap.without do # IM caches records, so we need to disable it to test this functionality. posts = assert_queries(2) do Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => "INNER JOIN comments on comments.post_id = posts.id", :conditions => "comments.body like 'Thank you%'", :order => 'posts.id') end @@ -823,7 +819,7 @@ class EagerAssociationTest < ActiveRecord::TestCase end assert_equal [posts(:welcome)], posts assert_equal authors(:david), assert_no_queries { posts[0].author} - end + end def test_eager_loading_with_select_on_joined_table_preloads diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index 59fc13fe51..b13cb2d7a2 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -578,7 +578,7 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase @pirate.ship.mark_for_destruction assert !@pirate.reload.marked_for_destruction? - assert !@pirate.ship.target.reload.marked_for_destruction? + assert !@pirate.ship.marked_for_destruction? end # has_one @@ -1194,7 +1194,6 @@ class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::Tes self.use_transactional_fixtures = false def setup - ActiveRecord::IdentityMap.enabled = false # This tests use trick with double association, IM prevents that, so we disable it. @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") @pirate.create_ship(:name => 'titanic') end @@ -1210,10 +1209,6 @@ class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::Tes @pirate.non_validated_ship.name = '' assert @pirate.valid? end - - def teardown - ActiveRecord::IdentityMap.enabled = true - end end class TestAutosaveAssociationValidationsOnABelongsToAssociation < ActiveRecord::TestCase diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index df77bc5af2..7086af614f 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -292,6 +292,7 @@ class IdentityMapTest < ActiveRecord::TestCase assert_equal [posts(:welcome)], posts assert_equal authors(:david), assert_no_queries { posts[0].author} end +<<<<<<< HEAD ############################################################################## # Behaviour releated to saving failures diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index 20a24c38fa..92af53d56f 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -551,7 +551,6 @@ module NestedAttributesOnACollectionAssociationTests assert_equal 'Grace OMalley', @child_1.reload.name end - def test_should_not_overwrite_unsaved_updates_when_loading_association @pirate.reload @pirate.send(association_setter, [{ :id => @child_1.id, :name => 'Grace OMalley' }]) diff --git a/activerecord/test/cases/readonly_test.rb b/activerecord/test/cases/readonly_test.rb index 448c8f8796..98011f40a4 100644 --- a/activerecord/test/cases/readonly_test.rb +++ b/activerecord/test/cases/readonly_test.rb @@ -40,10 +40,6 @@ class ReadOnlyTest < ActiveRecord::TestCase def test_find_with_joins_option_implies_readonly - # We disable IM, becouse we want to check default settings here - # adding readonly(false) does not update readonly status with IM - # (see corresponding test in IM) - ActiveRecord::IdentityMap.without do # Blank joins don't count. Developer.joins(' ').each { |d| assert !d.readonly? } Developer.joins(' ').readonly(false).each { |d| assert !d.readonly? } @@ -51,7 +47,6 @@ class ReadOnlyTest < ActiveRecord::TestCase # Others do. Developer.joins(', projects').each { |d| assert d.readonly? } Developer.joins(', projects').readonly(false).each { |d| assert !d.readonly? } - end end @@ -77,10 +72,6 @@ class ReadOnlyTest < ActiveRecord::TestCase end def test_readonly_scoping - # We disable IM, becouse we want to check default settings here - # adding readonly(false) does not update readonly status with IM - # (see corresponding test in IM) - ActiveRecord::IdentityMap.without do Post.send(:with_scope, :find => { :conditions => '1=1' }) do assert !Post.find(1).readonly? assert Post.readonly(true).find(1).readonly? @@ -108,7 +99,6 @@ class ReadOnlyTest < ActiveRecord::TestCase assert Post.readonly.find(1).readonly? assert !Post.readonly(false).find(1).readonly? end - end end def test_association_collection_method_missing_scoping_not_readonly -- cgit v1.2.3 From 9fe0dbf8bda4d5e8fb22a80e77d04e19e1866c5f Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 20 Oct 2010 16:13:49 -0300 Subject: Ups, forgot to remove one conflict tag from previous commit. --- activerecord/test/cases/identity_map_test.rb | 1 - 1 file changed, 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index 7086af614f..df77bc5af2 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -292,7 +292,6 @@ class IdentityMapTest < ActiveRecord::TestCase assert_equal [posts(:welcome)], posts assert_equal authors(:david), assert_no_queries { posts[0].author} end -<<<<<<< HEAD ############################################################################## # Behaviour releated to saving failures -- cgit v1.2.3 From 4015819adac4e4fcc96a3da4c9873359ea6ce230 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 20 Oct 2010 18:59:09 -0300 Subject: Fix number of queries performed in tests. --- activerecord/test/cases/associations/eager_test.rb | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index c00b8a1cde..16c5176e4f 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -170,7 +170,7 @@ class EagerAssociationTest < ActiveRecord::TestCase author = authors(:david) post = author.post_about_thinking_with_last_comment last_comment = post.last_comment - author = assert_queries(3) { Author.find(author.id, :include => {:post_about_thinking_with_last_comment => :last_comment})} # find the author, then find the posts, then find the comments + author = assert_queries(2) { Author.find(author.id, :include => {:post_about_thinking_with_last_comment => :last_comment})} # find the author, then find the posts, then find the comments assert_no_queries do assert_equal post, author.post_about_thinking_with_last_comment assert_equal last_comment, author.post_about_thinking_with_last_comment.last_comment @@ -181,7 +181,7 @@ class EagerAssociationTest < ActiveRecord::TestCase post = posts(:welcome) author = post.author author_address = author.author_address - post = assert_queries(3) { Post.find(post.id, :include => {:author_with_address => :author_address}) } # find the post, then find the author, then find the address + post = assert_queries(2) { Post.find(post.id, :include => {:author_with_address => :author_address}) } # find the post, then find the author, then find the address assert_no_queries do assert_equal author, post.author_with_address assert_equal author_address, post.author_with_address.author_address @@ -789,18 +789,18 @@ class EagerAssociationTest < ActiveRecord::TestCase assert_equal [posts(:welcome)], posts assert_equal authors(:david), assert_no_queries { posts[0].author} - posts = assert_queries(2) do + posts = assert_queries(1) do Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => [:comments], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id') end assert_equal [posts(:welcome)], posts assert_equal authors(:david), assert_no_queries { posts[0].author} - posts = assert_queries(2) do + posts = assert_queries(1) do Post.find(:all, :include => :author, :joins => {:taggings => :tag}, :conditions => "tags.name = 'General'", :order => 'posts.id') end assert_equal posts(:welcome, :thinking), posts - posts = assert_queries(2) do + posts = assert_queries(1) do Post.find(:all, :include => :author, :joins => {:taggings => {:tag => :taggings}}, :conditions => "taggings_tags.super_tag_id=2", :order => 'posts.id') end assert_equal posts(:welcome, :thinking), posts @@ -814,7 +814,7 @@ class EagerAssociationTest < ActiveRecord::TestCase assert_equal [posts(:welcome)], posts assert_equal authors(:david), assert_no_queries { posts[0].author} - posts = assert_queries(2) do + posts = assert_queries(1) do Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => ["INNER JOIN comments on comments.post_id = posts.id"], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id') end assert_equal [posts(:welcome)], posts -- cgit v1.2.3 From edb69b9be3be8ea8477004625d1ddf3f3de37d77 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 20 Oct 2010 18:59:59 -0300 Subject: Call super setup in this test. --- activerecord/test/cases/autosave_association_test.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index b13cb2d7a2..79cb3884a9 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -1196,6 +1196,7 @@ class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::Tes def setup @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") @pirate.create_ship(:name => 'titanic') + super end test "should automatically validate associations with :validate => true" do @@ -1204,7 +1205,7 @@ class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::Tes assert !@pirate.valid? end - test "should not automatically validate associations without :validate => true" do + test "should not automatically asd validate associations without :validate => true" do assert @pirate.valid? @pirate.non_validated_ship.name = '' assert @pirate.valid? -- cgit v1.2.3 From 4a0a1605cdee91bb8c9d3c1cb5989efa550a3816 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 20 Oct 2010 19:00:25 -0300 Subject: Clear IdentityMap before continue this test, we can do this here because store_full_sti_class is not supposed to change during "runtime". --- .../test/cases/associations/eager_load_includes_full_sti_class_test.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb index fb59f63f91..d75791cab9 100644 --- a/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb +++ b/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb @@ -27,6 +27,7 @@ class EagerLoadIncludeFullStiClassNamesTest < ActiveRecord::TestCase post = Namespaced::Post.find_by_title( 'Great stuff', :include => :tagging ) assert_nil post.tagging + ActiveRecord::IdentityMap.clear ActiveRecord::Base.store_full_sti_class = true post = Namespaced::Post.find_by_title( 'Great stuff', :include => :tagging ) assert_instance_of Tagging, post.tagging -- cgit v1.2.3 From 7892543a88e5ec2329e3834a591a7b3b80d165f0 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 20 Oct 2010 19:13:18 -0300 Subject: Don't change tests, fix code: if locking is enabled skip IM. --- activerecord/test/cases/locking_test.rb | 13 ------------- 1 file changed, 13 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb index 5ceb19e7c8..4ddcdc010b 100644 --- a/activerecord/test/cases/locking_test.rb +++ b/activerecord/test/cases/locking_test.rb @@ -15,11 +15,6 @@ class ReadonlyFirstNamePerson < Person attr_readonly :first_name end -# Becouse of introduction of IdentityMap optimistic locking should only be needed -# in multithreaded applications, or when more then one software operates on database. -# -# I'm using ActiveRecord::IdentityMap.without to prevent Identity map from -# using one record here. class OptimisticLockingTest < ActiveRecord::TestCase fixtures :people, :legacy_things, :references @@ -28,10 +23,6 @@ class OptimisticLockingTest < ActiveRecord::TestCase # of a test (see test_increment_counter_*). self.use_transactional_fixtures = false - def setup - ActiveRecord::IdentityMap.enabled = false - end - def test_lock_existing p1 = Person.find(1) p2 = Person.find(1) @@ -224,10 +215,6 @@ class OptimisticLockingTest < ActiveRecord::TestCase end end - def teardown - ActiveRecord::IdentityMap.enabled = true - end - private def add_counter_column_to(model, col='test_count') -- cgit v1.2.3 From 6cd1224f2eae69a44c820918657408b7650c1288 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Wed, 20 Oct 2010 19:18:30 -0300 Subject: Update number of queries executed instead of avoiding IM. --- activerecord/test/cases/relations_test.rb | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index eb268017f8..2809554e4f 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -263,13 +263,12 @@ class RelationTest < ActiveRecord::TestCase end def test_find_with_preloaded_associations - ActiveRecord::IdentityMap.without do assert_queries(2) do posts = Post.preload(:comments) assert posts.first.comments.first end - assert_queries(2) do + assert_queries(1) do posts = Post.preload(:comments).to_a assert posts.first.comments.first end @@ -279,27 +278,25 @@ class RelationTest < ActiveRecord::TestCase assert posts.first.author end - assert_queries(2) do + assert_queries(1) do posts = Post.preload(:author).to_a assert posts.first.author end - assert_queries(3) do + assert_queries(1) do posts = Post.preload(:author, :comments).to_a assert posts.first.author assert posts.first.comments.first end - end end def test_find_with_included_associations - ActiveRecord::IdentityMap.without do assert_queries(2) do posts = Post.includes(:comments) assert posts.first.comments.first end - assert_queries(2) do + assert_queries(1) do posts = Post.scoped.includes(:comments) assert posts.first.comments.first end @@ -309,12 +306,11 @@ class RelationTest < ActiveRecord::TestCase assert posts.first.author end - assert_queries(3) do + assert_queries(1) do posts = Post.includes(:author, :comments).to_a assert posts.first.author assert posts.first.comments.first end - end end def test_default_scope_with_conditions_string -- cgit v1.2.3 From 1c88d59891d11bd60a07f35a15c0043e0f8cf28a Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Thu, 18 Nov 2010 11:03:25 -0300 Subject: Add test using identity map and select. --- activerecord/test/cases/identity_map_test.rb | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index df77bc5af2..74d4cb0bfb 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -366,6 +366,20 @@ class IdentityMapTest < ActiveRecord::TestCase assert comment.save end + def test_find_using_select_and_identity_map + author_id, author = Author.select('id').first, Author.first + + assert_equal author_id, author + assert_same author_id, author + assert_not_nil author.name + + post, post_id = Post.first, Post.select('id').first + + assert_equal post_id, post + assert_same post_id, post + assert_not_nil post.title + end + # Currently AR is not allowing changing primary key (see Persistence#update) # So we ignore it. If this changes, this test needs to be uncommented. # def test_updating_of_pkey -- cgit v1.2.3 From bda16eb0920780509467bcf051d1a01639357903 Mon Sep 17 00:00:00 2001 From: Chiel Wester Date: Mon, 13 Dec 2010 15:06:23 +0100 Subject: Only call save on belongs_to associations if the record has changed or any nested associations have changed (resolves #3353) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: José Valim --- activerecord/test/cases/autosave_association_test.rb | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index fbf7121468..27aee400f9 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -667,10 +667,21 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase end end + @ship.pirate.catchphrase = "Changed Catchphrase" + assert_raise(RuntimeError) { assert !@ship.save } assert_not_nil @ship.reload.pirate end + def test_should_save_changed_child_objects_if_parent_is_saved + @pirate = @ship.create_pirate(:catchphrase => "Don' botharrr talkin' like one, savvy?") + @parrot = @pirate.parrots.create!(:name => 'Posideons Killer') + @parrot.name = "NewName" + @ship.save + + assert_equal 'NewName', @parrot.reload.name + end + # has_many & has_and_belongs_to %w{ parrots birds }.each do |association_name| define_method("test_should_destroy_#{association_name}_as_part_of_the_save_transaction_if_they_were_marked_for_destroyal") do -- cgit v1.2.3 From a1ca1e85a9ccefd72db4dc700a894c5bd7db53de Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 13 Dec 2010 11:39:31 -0800 Subject: persisted? should be able to return a truthy object --- activerecord/test/cases/transactions_test.rb | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb index b0ccd71836..110a18772f 100644 --- a/activerecord/test/cases/transactions_test.rb +++ b/activerecord/test/cases/transactions_test.rb @@ -370,23 +370,23 @@ class TransactionTest < ActiveRecord::TestCase assert topic_2.save @first.save @second.destroy - assert_equal true, topic_1.persisted? + assert topic_1.persisted?, 'persisted' assert_not_nil topic_1.id - assert_equal true, topic_2.persisted? + assert topic_2.persisted?, 'persisted' assert_not_nil topic_2.id - assert_equal true, @first.persisted? + assert @first.persisted?, 'persisted' assert_not_nil @first.id - assert_equal true, @second.destroyed? + assert @second.destroyed?, 'destroyed' raise ActiveRecord::Rollback end - assert_equal false, topic_1.persisted? + assert !topic_1.persisted?, 'not persisted' assert_nil topic_1.id - assert_equal false, topic_2.persisted? + assert !topic_2.persisted?, 'not persisted' assert_nil topic_2.id - assert_equal true, @first.persisted? + assert @first.persisted?, 'persisted' assert_not_nil @first.id - assert_equal false, @second.destroyed? + assert !@second.destroyed?, 'not destroyed' end if current_adapter?(:PostgreSQLAdapter) && defined?(PGconn::PQTRANS_IDLE) -- cgit v1.2.3 From 08ccca764498909faa2e4f9c69cee911e6395602 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 13 Dec 2010 13:49:39 -0800 Subject: fixing whitespace errors --- .../test/cases/associations/inner_join_association_test.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb index 780eabc443..da2a81e98a 100644 --- a/activerecord/test/cases/associations/inner_join_association_test.rb +++ b/activerecord/test/cases/associations/inner_join_association_test.rb @@ -65,21 +65,21 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase authors_with_welcoming_post_titles = Author.calculate(:count, 'authors.id', :joins => :posts, :distinct => true, :conditions => "posts.title like 'Welcome%'") assert_equal real_count, authors_with_welcoming_post_titles, "inner join and conditions should have only returned authors posting titles starting with 'Welcome'" end - + def test_find_with_sti_join scope = Post.joins(:special_comments).where(:id => posts(:sti_comments).id) - + # The join should match SpecialComment and its subclasses only assert scope.where("comments.type" => "Comment").empty? assert !scope.where("comments.type" => "SpecialComment").empty? assert !scope.where("comments.type" => "SubSpecialComment").empty? end - + def test_find_with_conditions_on_reflection assert !posts(:welcome).comments.empty? assert Post.joins(:nonexistant_comments).where(:id => posts(:welcome).id).empty? # [sic!] end - + def test_find_with_conditions_on_through_reflection assert !posts(:welcome).tags.empty? assert Post.joins(:misc_tags).where(:id => posts(:welcome).id).empty? -- cgit v1.2.3 From 7bffa9dd01cdef3088e0d33fabd5fc07eb35c9d9 Mon Sep 17 00:00:00 2001 From: Joe Hannon Date: Sun, 2 May 2010 16:26:02 -0700 Subject: add test which fails for has_many through self join [#4361 state:open] --- .../test/cases/associations/has_many_through_associations_test.rb | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 52432b0428..fe60e676d6 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -388,6 +388,13 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase ].each {|block| assert_raise(ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection, &block) } end + def test_has_many_association_through_a_has_many_association_to_self + sarah = Person.create!(:first_name => 'Sarah', :primary_contact_id => people(:susan).id, :gender => 'F', :number1_fan_id => 1) + john = Person.create!(:first_name => 'John', :primary_contact_id => sarah.id, :gender => 'M', :number1_fan_id => 1) + assert_equal sarah.agents, [john] + assert_equal people(:susan).agents_of_agents, [john] + end + def test_collection_singular_ids_getter_with_string_primary_keys book = books(:awdr) assert_equal 2, book.subscriber_ids.size -- cgit v1.2.3 From 5d37ff6bb2b1f948034bf06e450f2fdb8195c4e5 Mon Sep 17 00:00:00 2001 From: Ernie Miller Date: Mon, 3 May 2010 20:47:42 -0400 Subject: Fix hm:t to self table aliasing in construct_scope --- .../test/cases/associations/has_many_through_associations_test.rb | 2 +- activerecord/test/models/person.rb | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index fe60e676d6..34ae297275 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -392,7 +392,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase sarah = Person.create!(:first_name => 'Sarah', :primary_contact_id => people(:susan).id, :gender => 'F', :number1_fan_id => 1) john = Person.create!(:first_name => 'John', :primary_contact_id => sarah.id, :gender => 'M', :number1_fan_id => 1) assert_equal sarah.agents, [john] - assert_equal people(:susan).agents_of_agents, [john] + assert_equal people(:susan).agents.map(&:agents).flatten, people(:susan).agents_of_agents end def test_collection_singular_ids_getter_with_string_primary_keys diff --git a/activerecord/test/models/person.rb b/activerecord/test/models/person.rb index 951ec93c53..bee89de042 100644 --- a/activerecord/test/models/person.rb +++ b/activerecord/test/models/person.rb @@ -12,6 +12,7 @@ class Person < ActiveRecord::Base belongs_to :primary_contact, :class_name => 'Person' has_many :agents, :class_name => 'Person', :foreign_key => 'primary_contact_id' + has_many :agents_of_agents, :through => :agents, :source => :agents belongs_to :number1_fan, :class_name => 'Person' scope :males, :conditions => { :gender => 'M' } -- cgit v1.2.3 From eba76640862d071d89c846f8624d1e651d872794 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sun, 12 Dec 2010 16:35:27 +0000 Subject: Respect the default_scope on a join model when reading a through association --- .../cases/associations/has_many_through_associations_test.rb | 4 ++++ .../cases/associations/has_one_through_associations_test.rb | 10 +++++++++- activerecord/test/models/author.rb | 4 ++++ activerecord/test/models/contract.rb | 2 +- activerecord/test/models/post.rb | 7 +++++++ 5 files changed, 25 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 34ae297275..113d0f6d73 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -462,4 +462,8 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase post.people << people(:michael) assert_equal readers + 1, post.readers.size end + + def test_has_many_through_with_default_scope_on_join_model + assert_equal posts(:welcome).comments, authors(:david).comments_on_first_posts + end end diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb index ac43e571cb..93a4f498d0 100644 --- a/activerecord/test/cases/associations/has_one_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb @@ -9,9 +9,13 @@ require 'models/member_detail' require 'models/minivan' require 'models/dashboard' require 'models/speedometer' +require 'models/author' +require 'models/post' +require 'models/comment' class HasOneThroughAssociationsTest < ActiveRecord::TestCase - fixtures :member_types, :members, :clubs, :memberships, :sponsors, :organizations, :minivans, :dashboards, :speedometers + fixtures :member_types, :members, :clubs, :memberships, :sponsors, :organizations, :minivans, + :dashboards, :speedometers, :authors, :posts, :comments def setup @member = members(:groucho) @@ -229,4 +233,8 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase minivan.dashboard end end + + def test_has_one_through_with_default_scope_on_join_model + assert_equal posts(:welcome).comments.first, authors(:david).comment_on_first_posts + end end diff --git a/activerecord/test/models/author.rb b/activerecord/test/models/author.rb index 34bfd2d881..29ee50e801 100644 --- a/activerecord/test/models/author.rb +++ b/activerecord/test/models/author.rb @@ -26,6 +26,10 @@ class Author < ActiveRecord::Base has_many :comments_with_order_and_conditions, :through => :posts, :source => :comments, :order => 'comments.body', :conditions => "comments.body like 'Thank%'" has_many :comments_with_include, :through => :posts, :source => :comments, :include => :post + has_many :first_posts + has_many :comments_on_first_posts, :through => :first_posts, :source => :comments, :order => 'posts.id desc, comments.id asc' + has_one :comment_on_first_posts, :through => :first_posts, :source => :comments, :order => 'posts.id desc, comments.id asc' + has_many :thinking_posts, :class_name => 'Post', :conditions => { :title => 'So I was thinking' }, :dependent => :delete_all has_many :welcome_posts, :class_name => 'Post', :conditions => { :title => 'Welcome to the weblog' } diff --git a/activerecord/test/models/contract.rb b/activerecord/test/models/contract.rb index 606c99cd4e..94fd48e12a 100644 --- a/activerecord/test/models/contract.rb +++ b/activerecord/test/models/contract.rb @@ -1,4 +1,4 @@ class Contract < ActiveRecord::Base belongs_to :company belongs_to :developer -end \ No newline at end of file +end diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index 61e782ff14..164b499bf0 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -119,3 +119,10 @@ class PostForAuthor < ActiveRecord::Base cattr_accessor :selected_author default_scope lambda { where(:author_id => PostForAuthor.selected_author) } end + +class FirstPost < ActiveRecord::Base + self.table_name = 'posts' + default_scope where(:id => 1) + has_many :comments, :foreign_key => :post_id + has_one :comment, :foreign_key => :post_id +end -- cgit v1.2.3 From 491ce5b6ce1a3af42d02efff9a2e42b1a8980553 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sun, 12 Dec 2010 17:03:41 +0000 Subject: Verify that creating a has_many through record where there is a default_scope on the join model works correctly (creates the join record with the default scope applied) --- .../cases/associations/has_many_through_associations_test.rb | 7 +++++++ activerecord/test/models/author.rb | 4 ++++ activerecord/test/models/categorization.rb | 11 ++++++++++- activerecord/test/schema/schema.rb | 1 + 4 files changed, 22 insertions(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 113d0f6d73..44ff01ddc0 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -17,6 +17,8 @@ require 'models/developer' require 'models/subscriber' require 'models/book' require 'models/subscription' +require 'models/categorization' +require 'models/category' class HasManyThroughAssociationsTest < ActiveRecord::TestCase fixtures :posts, :readers, :people, :comments, :authors, @@ -466,4 +468,9 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase def test_has_many_through_with_default_scope_on_join_model assert_equal posts(:welcome).comments, authors(:david).comments_on_first_posts end + + def test_create_has_many_through_with_default_scope_on_join_model + category = authors(:david).special_categories.create(:name => "Foo") + assert_equal 1, category.categorizations.where(:special => true).count + end end diff --git a/activerecord/test/models/author.rb b/activerecord/test/models/author.rb index 29ee50e801..fd6d2b384a 100644 --- a/activerecord/test/models/author.rb +++ b/activerecord/test/models/author.rb @@ -77,6 +77,10 @@ class Author < ActiveRecord::Base has_many :categorizations has_many :categories, :through => :categorizations + has_many :special_categorizations + has_many :special_categories, :through => :special_categorizations, :source => :category + has_one :special_category, :through => :special_categorizations, :source => :category + has_many :categories_like_general, :through => :categorizations, :source => :category, :class_name => 'Category', :conditions => { :name => 'General' } has_many :categorized_posts, :through => :categorizations, :source => :post diff --git a/activerecord/test/models/categorization.rb b/activerecord/test/models/categorization.rb index 10594323ff..b3fc29fa15 100644 --- a/activerecord/test/models/categorization.rb +++ b/activerecord/test/models/categorization.rb @@ -2,4 +2,13 @@ class Categorization < ActiveRecord::Base belongs_to :post belongs_to :category belongs_to :author -end \ No newline at end of file +end + +class SpecialCategorization < ActiveRecord::Base + self.table_name = 'categorizations' + + default_scope where(:special => true) + + belongs_to :author + belongs_to :category +end diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index d4eb56c4d7..177045ac51 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -112,6 +112,7 @@ ActiveRecord::Schema.define do t.column :category_id, :integer t.column :post_id, :integer t.column :author_id, :integer + t.column :special, :boolean end create_table :citations, :force => true do |t| -- cgit v1.2.3 From 15984dbe35651e64dcff69f8e48fca156c380df2 Mon Sep 17 00:00:00 2001 From: Pivotal Labs Date: Fri, 9 Jan 2009 12:13:17 -0800 Subject: test for eager load of has_one association with condition on the through table --- activerecord/test/cases/associations/eager_test.rb | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index c96ca90750..34a1cdeebe 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -17,18 +17,26 @@ require 'models/subscription' require 'models/book' require 'models/developer' require 'models/project' +require 'models/member' +require 'models/membership' +require 'models/club' class EagerAssociationTest < ActiveRecord::TestCase fixtures :posts, :comments, :authors, :author_addresses, :categories, :categories_posts, :companies, :accounts, :tags, :taggings, :people, :readers, :owners, :pets, :author_favorites, :jobs, :references, :subscribers, :subscriptions, :books, - :developers, :projects, :developers_projects + :developers, :projects, :developers_projects, :members, :memberships, :clubs def setup # preheat table existence caches Comment.find_by_id(1) end + def test_eager_with_has_one_through_join_model_with_conditions_on_the_through + member = Member.find(members(:some_other_guy).id, :include => :favourite_club) + assert_nil member.favourite_club + end + def test_loading_with_one_association posts = Post.find(:all, :include => :comments) post = posts.find { |p| p.id == 1 } -- cgit v1.2.3 From aa40543022303d8a1b695e73ed71406c0da15bde Mon Sep 17 00:00:00 2001 From: Franck Verrot Date: Thu, 18 Nov 2010 09:01:45 +0100 Subject: Provide test for #4840: to_xml doesn't work in such case: Event.select('title as t').to_xml --- activerecord/test/cases/xml_serialization_test.rb | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/xml_serialization_test.rb b/activerecord/test/cases/xml_serialization_test.rb index 2003e25e35..a6074b23e7 100644 --- a/activerecord/test/cases/xml_serialization_test.rb +++ b/activerecord/test/cases/xml_serialization_test.rb @@ -262,4 +262,10 @@ class DatabaseConnectedXmlSerializationTest < ActiveRecord::TestCase assert array.include? 'github' end + def test_should_support_aliased_attributes + xml = Author.select("name as firstname").to_xml + array = Hash.from_xml(xml)['authors'] + assert_equal array.size, array.select { |author| author.has_key? 'firstname' }.size + end + end -- cgit v1.2.3 From 96bae30538951367a82235785e7dba3577b50a5a Mon Sep 17 00:00:00 2001 From: Pavel Gorbokon Date: Wed, 24 Nov 2010 10:17:49 +0200 Subject: Replace rudimentary named_scope with scope. [#6052 state:resolved] * rename method names (actually in tests) * rename instance variable @_named_scopes_cache to @_scopes_cache * rename references in doc comments * don't touch CHANGELOG :) --- activerecord/test/cases/named_scope_test.rb | 42 ++++++++++++------------ activerecord/test/cases/relation_scoping_test.rb | 2 +- activerecord/test/cases/relations_test.rb | 6 ++-- 3 files changed, 25 insertions(+), 25 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb index 6ac3e3fc56..ed5e1e0cba 100644 --- a/activerecord/test/cases/named_scope_test.rb +++ b/activerecord/test/cases/named_scope_test.rb @@ -141,26 +141,26 @@ class NamedScopeTest < ActiveRecord::TestCase assert_equal 1, Topic.multiple_extensions.extension_one end - def test_has_many_associations_have_access_to_named_scopes + def test_has_many_associations_have_access_to_scopes assert_not_equal Post.containing_the_letter_a, authors(:david).posts assert !Post.containing_the_letter_a.empty? assert_equal authors(:david).posts & Post.containing_the_letter_a, authors(:david).posts.containing_the_letter_a end - def test_named_scope_with_STI + def test_scope_with_STI assert_equal 3,Post.containing_the_letter_a.count assert_equal 1,SpecialPost.containing_the_letter_a.count end - def test_has_many_through_associations_have_access_to_named_scopes + def test_has_many_through_associations_have_access_to_scopes assert_not_equal Comment.containing_the_letter_e, authors(:david).comments assert !Comment.containing_the_letter_e.empty? assert_equal authors(:david).comments & Comment.containing_the_letter_e, authors(:david).comments.containing_the_letter_e end - def test_named_scopes_honor_current_scopes_from_when_defined + def test_scopes_honor_current_scopes_from_when_defined assert !Post.ranked_by_comments.limit_by(5).empty? assert !authors(:david).posts.ranked_by_comments.limit_by(5).empty? assert_not_equal Post.ranked_by_comments.limit_by(5), authors(:david).posts.ranked_by_comments.limit_by(5) @@ -236,7 +236,7 @@ class NamedScopeTest < ActiveRecord::TestCase end end - def test_any_should_not_fire_query_if_named_scope_loaded + def test_any_should_not_fire_query_if_scope_loaded topics = Topic.base topics.collect # force load assert_no_queries { assert topics.any? } @@ -259,7 +259,7 @@ class NamedScopeTest < ActiveRecord::TestCase end end - def test_many_should_not_fire_query_if_named_scope_loaded + def test_many_should_not_fire_query_if_scope_loaded topics = Topic.base topics.collect # force load assert_no_queries { assert topics.many? } @@ -276,27 +276,27 @@ class NamedScopeTest < ActiveRecord::TestCase assert Topic.base.many? end - def test_should_build_on_top_of_named_scope + def test_should_build_on_top_of_scope topic = Topic.approved.build({}) assert topic.approved end - def test_should_build_new_on_top_of_named_scope + def test_should_build_new_on_top_of_scope topic = Topic.approved.new assert topic.approved end - def test_should_create_on_top_of_named_scope + def test_should_create_on_top_of_scope topic = Topic.approved.create({}) assert topic.approved end - def test_should_create_with_bang_on_top_of_named_scope + def test_should_create_with_bang_on_top_of_scope topic = Topic.approved.create!({}) assert topic.approved end - def test_should_build_on_top_of_chained_named_scopes + def test_should_build_on_top_of_chained_scopes topic = Topic.approved.by_lifo.build({}) assert topic.approved assert_equal 'lifo', topic.author_name @@ -310,7 +310,7 @@ class NamedScopeTest < ActiveRecord::TestCase assert_kind_of Topic, Topic.approved.sample end - def test_should_use_where_in_query_for_named_scope + def test_should_use_where_in_query_for_scope assert_equal Developer.find_all_by_name('Jamis').to_set, Developer.find_all_by_id(Developer.jamises).to_set end @@ -361,7 +361,7 @@ class NamedScopeTest < ActiveRecord::TestCase assert_equal [posts(:sti_comments)], Post.with_special_comments.with_post(4).all.uniq end - def test_named_scopes_batch_finders + def test_scopes_batch_finders assert_equal 3, Topic.approved.count assert_queries(4) do @@ -381,7 +381,7 @@ class NamedScopeTest < ActiveRecord::TestCase end end - def test_named_scopes_with_reserved_names + def test_scopes_with_reserved_names class << Topic def public_method; end public :public_method @@ -400,7 +400,7 @@ class NamedScopeTest < ActiveRecord::TestCase end end - def test_named_scopes_on_relations + def test_scopes_on_relations # Topic.replied approved_topics = Topic.scoped.approved.order('id DESC') assert_equal topics(:fourth), approved_topics.first @@ -409,19 +409,19 @@ class NamedScopeTest < ActiveRecord::TestCase assert_equal topics(:third), replied_approved_topics.first end - def test_index_on_named_scope + def test_index_on_scope approved = Topic.approved.order('id ASC') assert_equal topics(:second), approved[0] assert approved.loaded? end - def test_nested_named_scopes_queries_size + def test_nested_scopes_queries_size assert_queries(1) do Topic.approved.by_lifo.replied.written_before(Time.now).all end end - def test_named_scopes_are_cached_on_associations + def test_scopes_are_cached_on_associations post = posts(:welcome) assert_equal post.comments.containing_the_letter_e.object_id, post.comments.containing_the_letter_e.object_id @@ -430,7 +430,7 @@ class NamedScopeTest < ActiveRecord::TestCase assert_no_queries { post.comments.containing_the_letter_e.all } end - def test_named_scopes_with_arguments_are_cached_on_associations + def test_scopes_with_arguments_are_cached_on_associations post = posts(:welcome) one = post.comments.limit_by(1).all @@ -443,7 +443,7 @@ class NamedScopeTest < ActiveRecord::TestCase assert_no_queries { post.comments.limit_by(2).all } end - def test_named_scopes_are_reset_on_association_reload + def test_scopes_are_reset_on_association_reload post = posts(:welcome) [:destroy_all, :reset, :delete_all].each do |method| @@ -453,7 +453,7 @@ class NamedScopeTest < ActiveRecord::TestCase end end - def test_named_scoped_are_lazy_loaded_if_table_still_does_not_exist + def test_scoped_are_lazy_loaded_if_table_still_does_not_exist assert_nothing_raised do require "models/without_table" end diff --git a/activerecord/test/cases/relation_scoping_test.rb b/activerecord/test/cases/relation_scoping_test.rb index 1678e631e5..f113a9c516 100644 --- a/activerecord/test/cases/relation_scoping_test.rb +++ b/activerecord/test/cases/relation_scoping_test.rb @@ -422,7 +422,7 @@ class DefaultScopingTest < ActiveRecord::TestCase assert_equal expected, received end - def test_named_scope_overwrites_default + def test_scope_overwrites_default expected = Developer.find(:all, :order => 'salary DESC, name DESC').collect { |dev| dev.name } received = DeveloperOrderedBySalary.by_name.find(:all).collect { |dev| dev.name } assert_equal expected, received diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 1682f34a1d..0b106e3bcd 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -36,7 +36,7 @@ class RelationTest < ActiveRecord::TestCase assert_equal [], relation.bind_values end - def test_two_named_scopes_with_includes_should_not_drop_any_include + def test_two_scopes_with_includes_should_not_drop_any_include car = Car.incl_engines.incl_tyres.first assert_no_queries { car.tyres.length } assert_no_queries { car.engines.length } @@ -248,7 +248,7 @@ class RelationTest < ActiveRecord::TestCase end end - def test_respond_to_class_methods_and_named_scopes + def test_respond_to_class_methods_and_scopes assert DeveloperOrderedBySalary.scoped.respond_to?(:all_ordered_by_name) assert Topic.scoped.respond_to?(:by_lifo) end @@ -754,7 +754,7 @@ class RelationTest < ActiveRecord::TestCase assert_equal 'zyke', FastCar.order('name desc').find(:first, :order => 'id').name end - def test_default_scope_order_with_named_scope_order + def test_default_scope_order_with_scope_order assert_equal 'zyke', CoolCar.order_using_new_style.limit(1).first.name assert_equal 'zyke', CoolCar.order_using_old_style.limit(1).first.name assert_equal 'zyke', FastCar.order_using_new_style.limit(1).first.name -- cgit v1.2.3 From 09ddca67acbb88e2fdd7300670839cbf647b2694 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Thu, 16 Dec 2010 00:40:03 +0000 Subject: Fix problem with duplicated records when a :uniq :through association is preloaded [#2447 state:resolved] --- activerecord/test/cases/associations/eager_test.rb | 9 ++++++++- .../cases/associations/has_many_through_associations_test.rb | 8 +++++++- 2 files changed, 15 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index 34a1cdeebe..d5262b1ee4 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -20,10 +20,11 @@ require 'models/project' require 'models/member' require 'models/membership' require 'models/club' +require 'models/categorization' class EagerAssociationTest < ActiveRecord::TestCase fixtures :posts, :comments, :authors, :author_addresses, :categories, :categories_posts, - :companies, :accounts, :tags, :taggings, :people, :readers, + :companies, :accounts, :tags, :taggings, :people, :readers, :categorizations, :owners, :pets, :author_favorites, :jobs, :references, :subscribers, :subscriptions, :books, :developers, :projects, :developers_projects, :members, :memberships, :clubs @@ -910,4 +911,10 @@ class EagerAssociationTest < ActiveRecord::TestCase assert_queries(2) { @tagging = Tagging.preload(:taggable).find(t.id) } assert_no_queries { assert ! @tagging.taggable } end + + def test_preloading_has_many_through_with_uniq + mary = Author.includes(:unique_categorized_posts).where(:id => authors(:mary).id).first + assert_equal 1, mary.unique_categorized_posts.length + assert_equal 1, mary.unique_categorized_post_ids.length + end end diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 44ff01ddc0..77bc369ecc 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -23,7 +23,7 @@ require 'models/category' class HasManyThroughAssociationsTest < ActiveRecord::TestCase fixtures :posts, :readers, :people, :comments, :authors, :owners, :pets, :toys, :jobs, :references, :companies, - :subscribers, :books, :subscriptions, :developers + :subscribers, :books, :subscriptions, :developers, :categorizations # Dummies to force column loads so query counts are clean. def setup @@ -473,4 +473,10 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase category = authors(:david).special_categories.create(:name => "Foo") assert_equal 1, category.categorizations.where(:special => true).count end + + def test_joining_has_many_through_with_uniq + mary = Author.joins(:unique_categorized_posts).where(:id => authors(:mary).id).first + assert_equal 1, mary.unique_categorized_posts.length + assert_equal 1, mary.unique_categorized_post_ids.length + end end -- cgit v1.2.3 From 14b880fd035fcdf807051398674c9aa89bd3b4d3 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Wed, 15 Dec 2010 23:27:15 +0000 Subject: Fix various issues with the :primary_key option in :through associations [#2421 state:resolved] --- activerecord/test/cases/associations/join_model_test.rb | 16 ++++++++++++++++ activerecord/test/cases/reflection_test.rb | 5 +++++ activerecord/test/models/categorization.rb | 3 +++ activerecord/test/models/post.rb | 10 ++++++++++ 4 files changed, 34 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb index 4581cb1acd..0a57c7883f 100644 --- a/activerecord/test/cases/associations/join_model_test.rb +++ b/activerecord/test/cases/associations/join_model_test.rb @@ -298,6 +298,22 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase assert_equal [authors(:mary)], posts(:authorless).authors end + def test_has_many_going_through_join_model_with_custom_primary_key + assert_equal [authors(:david)], posts(:thinking).authors_using_author_id + end + + def test_has_many_going_through_polymorphic_join_model_with_custom_primary_key + assert_equal [tags(:general)], posts(:eager_other).tags_using_author_id + end + + def test_has_many_through_with_custom_primary_key_on_belongs_to_source + assert_equal [authors(:david), authors(:david)], posts(:thinking).author_using_custom_pk + end + + def test_has_many_through_with_custom_primary_key_on_has_many_source + assert_equal [authors(:david)], posts(:thinking).authors_using_custom_pk + end + def test_both_scoped_and_explicit_joins_should_be_respected assert_nothing_raised do Post.send(:with_scope, :find => {:joins => "left outer join comments on comments.id = posts.id"}) do diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index 389ca9eae6..912e3c47bb 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -191,6 +191,11 @@ class ReflectionTest < ActiveRecord::TestCase assert_kind_of ThroughReflection, Subscriber.reflect_on_association(:books) end + def test_active_record_primary_key + assert_equal "nick", Subscriber.reflect_on_association(:subscriptions).active_record_primary_key.to_s + assert_equal "name", Author.reflect_on_association(:essay).active_record_primary_key.to_s + end + def test_collection_association assert Pirate.reflect_on_association(:birds).collection? assert Pirate.reflect_on_association(:parrots).collection? diff --git a/activerecord/test/models/categorization.rb b/activerecord/test/models/categorization.rb index b3fc29fa15..fdb0a11540 100644 --- a/activerecord/test/models/categorization.rb +++ b/activerecord/test/models/categorization.rb @@ -2,6 +2,9 @@ class Categorization < ActiveRecord::Base belongs_to :post belongs_to :category belongs_to :author + + belongs_to :author_using_custom_pk, :class_name => 'Author', :foreign_key => :author_id, :primary_key => :author_address_extra_id + has_many :authors_using_custom_pk, :class_name => 'Author', :foreign_key => :id, :primary_key => :category_id end class SpecialCategorization < ActiveRecord::Base diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index 164b499bf0..974e87d2bf 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -69,6 +69,16 @@ class Post < ActiveRecord::Base has_many :categorizations, :foreign_key => :category_id has_many :authors, :through => :categorizations + has_many :categorizations_using_author_id, :primary_key => :author_id, :foreign_key => :post_id, :class_name => 'Categorization' + has_many :authors_using_author_id, :through => :categorizations_using_author_id, :source => :author + + has_many :taggings_using_author_id, :primary_key => :author_id, :as => :taggable, :class_name => 'Tagging' + has_many :tags_using_author_id, :through => :taggings_using_author_id, :source => :tag + + has_many :standard_categorizations, :class_name => 'Categorization', :foreign_key => :post_id + has_many :author_using_custom_pk, :through => :standard_categorizations + has_many :authors_using_custom_pk, :through => :standard_categorizations + has_many :readers has_many :readers_with_person, :include => :person, :class_name => "Reader" has_many :people, :through => :readers -- cgit v1.2.3 From 40b15f9f389b9394b22cf36567269e54c66c9fc8 Mon Sep 17 00:00:00 2001 From: Piotr Sarnacki Date: Thu, 16 Dec 2010 22:20:42 +0100 Subject: ActiveRecord::Base.joins should allow single nil argument [#6181 state:resolved] --- activerecord/test/cases/relations_test.rb | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 0b106e3bcd..20bfafbc5e 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -184,6 +184,10 @@ class RelationTest < ActiveRecord::TestCase assert_equal [2, 4, 6, 8, 10], even_ids.sort end + def test_joins_with_nil_argument + assert_nothing_raised { DependentFirm.joins(nil).first } + end + def test_finding_with_hash_conditions_on_joined_table firms = DependentFirm.joins(:account).where({:name => 'RailsCore', :accounts => { :credit_limit => 55..60 }}).to_a assert_equal 1, firms.size -- cgit v1.2.3 From b8153fd5a18441567f787a33ca882acb3bb5088a Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Thu, 16 Dec 2010 10:29:13 +0000 Subject: Fix problem where wrong keys are used in JoinAssociation when an association goes :through a belongs_to [#2801 state:resolved] --- .../test/cases/associations/has_many_through_associations_test.rb | 7 +++++++ activerecord/test/cases/reflection_test.rb | 5 +++++ activerecord/test/models/post.rb | 1 + 3 files changed, 13 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 77bc369ecc..cf0eedbd13 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -479,4 +479,11 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase assert_equal 1, mary.unique_categorized_posts.length assert_equal 1, mary.unique_categorized_post_ids.length end + + def test_joining_has_many_through_belongs_to + posts = Post.joins(:author_categorizations). + where('categorizations.id' => categorizations(:mary_thinking_sti).id) + + assert_equal [posts(:eager_other)], posts + end end diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index 912e3c47bb..1e205714a7 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -191,6 +191,11 @@ class ReflectionTest < ActiveRecord::TestCase assert_kind_of ThroughReflection, Subscriber.reflect_on_association(:books) end + def test_association_primary_key + assert_equal "id", Author.reflect_on_association(:posts).association_primary_key.to_s + assert_equal "name", Author.reflect_on_association(:essay).association_primary_key.to_s + end + def test_active_record_primary_key assert_equal "nick", Subscriber.reflect_on_association(:subscriptions).active_record_primary_key.to_s assert_equal "name", Author.reflect_on_association(:essay).active_record_primary_key.to_s diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index 974e87d2bf..34ea49f731 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -38,6 +38,7 @@ class Post < ActiveRecord::Base end has_many :author_favorites, :through => :author + has_many :author_categorizations, :through => :author, :source => :categorizations has_many :comments_with_interpolated_conditions, :class_name => 'Comment', :conditions => ['#{"#{aliased_table_name}." rescue ""}body = ?', 'Thank you for the welcome'] -- cgit v1.2.3 From 834e5336a5d8a8250251e756385e39ebfb4917c3 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Fri, 17 Dec 2010 20:54:50 +0000 Subject: has_many associations with :dependent => :delete_all should update the counter cache when deleting records --- .../test/cases/associations/has_many_associations_test.rb | 12 ++++++++++++ activerecord/test/models/post.rb | 2 ++ activerecord/test/schema/schema.rb | 1 + 3 files changed, 15 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index fb772bb8e6..2b7ad3642a 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -616,6 +616,18 @@ class HasManyAssociationsTest < ActiveRecord::TestCase end end + def test_deleting_updates_counter_cache_with_dependent_delete_all + post = posts(:welcome) + + # Manually update the count as the tagging will have been added to the taggings association, + # rather than to the taggings_with_delete_all one (which is just a 'shadow' of the former) + post.update_attribute(:taggings_with_delete_all_count, post.taggings_with_delete_all.to_a.count) + + assert_difference "post.reload.taggings_with_delete_all_count", -1 do + post.taggings_with_delete_all.delete(post.taggings_with_delete_all.first) + end + end + def test_deleting_a_collection force_signal37_to_load_all_clients_of_firm companies(:first_firm).clients_of_firm.create("name" => "Another Client") diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index 34ea49f731..0083560ebe 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -59,6 +59,8 @@ class Post < ActiveRecord::Base end end + has_many :taggings_with_delete_all, :class_name => 'Tagging', :as => :taggable, :dependent => :delete_all + has_many :misc_tags, :through => :taggings, :source => :tag, :conditions => "tags.name = 'Misc'" has_many :funky_tags, :through => :taggings, :source => :tag has_many :super_tags, :through => :taggings diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 177045ac51..99761a4160 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -441,6 +441,7 @@ ActiveRecord::Schema.define do t.string :type t.integer :comments_count, :default => 0 t.integer :taggings_count, :default => 0 + t.integer :taggings_with_delete_all_count, :default => 0 end create_table :price_estimates, :force => true do |t| -- cgit v1.2.3 From 099a210c837daae692154add3b9da0a207825d35 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 20 Dec 2010 16:33:07 -0800 Subject: if there is no base name, we cannot determine a primary key --- activerecord/test/cases/base_test.rb | 2 ++ 1 file changed, 2 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 86d4a90fc4..dc5e912412 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -1069,6 +1069,7 @@ class BasicsTest < ActiveRecord::TestCase def test_define_attr_method_with_block k = Class.new( ActiveRecord::Base ) + k.primary_key = "id" k.send(:define_attr_method, :primary_key) { "sys_" + original_primary_key } assert_equal "sys_id", k.primary_key end @@ -1109,6 +1110,7 @@ class BasicsTest < ActiveRecord::TestCase def test_set_primary_key_with_block k = Class.new( ActiveRecord::Base ) + k.primary_key = 'id' k.set_primary_key { "sys_" + original_primary_key } assert_equal "sys_id", k.primary_key end -- cgit v1.2.3 From 207f266ccaaa9cd04cd2a7513ae5598c4358b510 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 20 Dec 2010 17:33:26 -0800 Subject: define_attr_method must serialize nil correctly --- activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb | 5 +++++ activerecord/test/cases/associations/join_model_test.rb | 4 ++++ activerecord/test/cases/base_test.rb | 5 +++++ 3 files changed, 14 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb index 234696adeb..b8abdface4 100644 --- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb @@ -9,6 +9,11 @@ module ActiveRecord :timeout => 100 end + def test_primary_key_returns_nil_for_no_pk + @conn.exec_query('create table ex(id int, data string)') + assert_nil @conn.primary_key('ex') + end + def test_connection_no_db assert_raises(ArgumentError) do Base.sqlite3_connection {} diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb index 0a57c7883f..58542bc939 100644 --- a/activerecord/test/cases/associations/join_model_test.rb +++ b/activerecord/test/cases/associations/join_model_test.rb @@ -512,6 +512,10 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase assert_nothing_raised { vertices(:vertex_1).sinks << vertices(:vertex_5) } end + def test_add_to_join_table_with_no_id + assert_nothing_raised { vertices(:vertex_1).sinks << vertices(:vertex_5) } + end + def test_has_many_through_collection_size_doesnt_load_target_if_not_loaded author = authors(:david) assert_equal 10, author.comments.size diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index dc5e912412..e186b2aea7 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -19,6 +19,7 @@ require 'models/minimalistic' require 'models/warehouse_thing' require 'models/parrot' require 'models/loose_person' +require 'models/edge' require 'rexml/document' require 'active_support/core_ext/exception' @@ -48,6 +49,10 @@ class Boolean < ActiveRecord::Base; end class BasicsTest < ActiveRecord::TestCase fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts + def test_primary_key_with_no_id + assert_nil Edge.primary_key + end + def test_select_symbol topic_ids = Topic.select(:id).map(&:id).sort assert_equal Topic.find(:all).map(&:id).sort, topic_ids -- cgit v1.2.3 From 3e64336647fefe598ff3b0775401e2c2c5d378d3 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 22 Dec 2010 18:22:54 -0800 Subject: removing SQL interpolation, please use scoping and attribute conditionals as a replacement --- activerecord/test/cases/associations/eager_test.rb | 4 ---- activerecord/test/models/post.rb | 3 --- 2 files changed, 7 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index d5262b1ee4..6efb0d57e4 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -658,10 +658,6 @@ class EagerAssociationTest < ActiveRecord::TestCase assert_equal people(:david, :susan), Person.find(:all, :include => [:readers, :primary_contact, :number1_fan], :conditions => "number1_fans_people.first_name like 'M%'", :order => 'people.id', :limit => 2, :offset => 0) end - def test_preload_with_interpolation - assert_equal [comments(:greetings)], Post.find(posts(:welcome).id, :include => :comments_with_interpolated_conditions).comments_with_interpolated_conditions - end - def test_polymorphic_type_condition post = Post.find(posts(:thinking).id, :include => :taggings) assert post.taggings.include?(taggings(:thinking_general)) diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index 0083560ebe..b51f7ff48f 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -40,9 +40,6 @@ class Post < ActiveRecord::Base has_many :author_favorites, :through => :author has_many :author_categorizations, :through => :author, :source => :categorizations - has_many :comments_with_interpolated_conditions, :class_name => 'Comment', - :conditions => ['#{"#{aliased_table_name}." rescue ""}body = ?', 'Thank you for the welcome'] - has_one :very_special_comment has_one :very_special_comment_with_post, :class_name => "VerySpecialComment", :include => :post has_many :special_comments -- cgit v1.2.3 From d9c8c47e3db89ca75de6ae9a8497659378ef0c1d Mon Sep 17 00:00:00 2001 From: Raimonds Simanovskis Date: Thu, 23 Dec 2010 23:11:32 +0800 Subject: Fix for default_scope tests to ensure comparing of equally sorted lists This is additional fix for commit ebc47465a5865ab91dc7d058d2d8a0cc961510d7 Respect the default_scope on a join model when reading a through association which otherwise was failing on Oracle (as it returned fixture comments in different order). --- .../test/cases/associations/has_many_through_associations_test.rb | 2 +- .../test/cases/associations/has_one_through_associations_test.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index cf0eedbd13..816b43ab9e 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -466,7 +466,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase end def test_has_many_through_with_default_scope_on_join_model - assert_equal posts(:welcome).comments, authors(:david).comments_on_first_posts + assert_equal posts(:welcome).comments.order('id').all, authors(:david).comments_on_first_posts end def test_create_has_many_through_with_default_scope_on_join_model diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb index 93a4f498d0..856214997c 100644 --- a/activerecord/test/cases/associations/has_one_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb @@ -235,6 +235,6 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase end def test_has_one_through_with_default_scope_on_join_model - assert_equal posts(:welcome).comments.first, authors(:david).comment_on_first_posts + assert_equal posts(:welcome).comments.order('id').first, authors(:david).comment_on_first_posts end end -- cgit v1.2.3 From c6db37e69b1ff07f7ad535d4752d0e6eb2d15bff Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sun, 19 Dec 2010 14:17:29 +0000 Subject: Don't allow a has_one association to go :through a collection association [#2976 state:resolved] --- .../cases/associations/has_one_through_associations_test.rb | 12 +++++++----- activerecord/test/models/author.rb | 4 +++- activerecord/test/models/member.rb | 9 ++++++--- 3 files changed, 16 insertions(+), 9 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb index 856214997c..f6307e6cf0 100644 --- a/activerecord/test/cases/associations/has_one_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb @@ -25,10 +25,6 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase assert_equal clubs(:boring_club), @member.club end - def test_has_one_through_with_has_many - assert_equal clubs(:moustache_club), @member.favourite_club - end - def test_creating_association_creates_through_record new_member = Member.create(:name => "Chris") new_member.club = Club.create(:name => "LRUG") @@ -235,6 +231,12 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase end def test_has_one_through_with_default_scope_on_join_model - assert_equal posts(:welcome).comments.order('id').first, authors(:david).comment_on_first_posts + assert_equal posts(:welcome).comments.order('id').first, authors(:david).comment_on_first_post + end + + def test_has_one_through_many_raises_exception + assert_raise(ActiveRecord::HasOneThroughCantAssociateThroughCollection) do + members(:groucho).club_through_many + end end end diff --git a/activerecord/test/models/author.rb b/activerecord/test/models/author.rb index fd6d2b384a..244c5ac4f5 100644 --- a/activerecord/test/models/author.rb +++ b/activerecord/test/models/author.rb @@ -28,7 +28,9 @@ class Author < ActiveRecord::Base has_many :first_posts has_many :comments_on_first_posts, :through => :first_posts, :source => :comments, :order => 'posts.id desc, comments.id asc' - has_one :comment_on_first_posts, :through => :first_posts, :source => :comments, :order => 'posts.id desc, comments.id asc' + + has_one :first_post + has_one :comment_on_first_post, :through => :first_post, :source => :comments, :order => 'posts.id desc, comments.id asc' has_many :thinking_posts, :class_name => 'Post', :conditions => { :title => 'So I was thinking' }, :dependent => :delete_all has_many :welcome_posts, :class_name => 'Post', :conditions => { :title => 'Welcome to the weblog' } diff --git a/activerecord/test/models/member.rb b/activerecord/test/models/member.rb index 255fb569d7..5b0a5ebf7f 100644 --- a/activerecord/test/models/member.rb +++ b/activerecord/test/models/member.rb @@ -1,12 +1,15 @@ class Member < ActiveRecord::Base has_one :current_membership - has_many :memberships + has_one :membership has_many :fellow_members, :through => :club, :source => :members has_one :club, :through => :current_membership - has_one :favourite_club, :through => :memberships, :conditions => ["memberships.favourite = ?", true], :source => :club + has_one :favourite_club, :through => :membership, :conditions => ["memberships.favourite = ?", true], :source => :club has_one :sponsor, :as => :sponsorable has_one :sponsor_club, :through => :sponsor has_one :member_detail has_one :organization, :through => :member_detail belongs_to :member_type -end \ No newline at end of file + + has_many :current_memberships + has_one :club_through_many, :through => :current_memberships, :source => :club +end -- cgit v1.2.3 From b79823832e6cd30a9f14f97ffdf1642d4d63d4ea Mon Sep 17 00:00:00 2001 From: Will Bryant Date: Thu, 13 Aug 2009 12:38:20 +1200 Subject: Verify that has_one :through preload respects the :conditions [#2976 state:resolved] --- .../cases/associations/has_one_through_associations_test.rb | 12 ++++++++++++ activerecord/test/models/member.rb | 1 + 2 files changed, 13 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb index f6307e6cf0..f6365e0216 100644 --- a/activerecord/test/cases/associations/has_one_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb @@ -84,6 +84,18 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase assert_not_nil assert_no_queries {members[0].sponsor_club} end + def test_has_one_through_with_conditions_eager_loading + # conditions on the through table + assert_equal clubs(:moustache_club), Member.find(@member.id, :include => :favourite_club).favourite_club + memberships(:membership_of_favourite_club).update_attribute(:favourite, false) + assert_equal nil, Member.find(@member.id, :include => :favourite_club).favourite_club + + # conditions on the source table + assert_equal clubs(:moustache_club), Member.find(@member.id, :include => :hairy_club).hairy_club + clubs(:moustache_club).update_attribute(:name, "Association of Clean-Shaven Persons") + assert_equal nil, Member.find(@member.id, :include => :hairy_club).hairy_club + end + def test_has_one_through_polymorphic_with_source_type assert_equal members(:groucho), clubs(:moustache_club).sponsored_member end diff --git a/activerecord/test/models/member.rb b/activerecord/test/models/member.rb index 5b0a5ebf7f..15ad6aedd3 100644 --- a/activerecord/test/models/member.rb +++ b/activerecord/test/models/member.rb @@ -4,6 +4,7 @@ class Member < ActiveRecord::Base has_many :fellow_members, :through => :club, :source => :members has_one :club, :through => :current_membership has_one :favourite_club, :through => :membership, :conditions => ["memberships.favourite = ?", true], :source => :club + has_one :hairy_club, :through => :membership, :conditions => {:clubs => {:name => "Moustache and Eyebrow Fancier Club"}}, :source => :club has_one :sponsor, :as => :sponsorable has_one :sponsor_club, :through => :sponsor has_one :member_detail -- cgit v1.2.3 From 85683f2a79dbf81130361cb6426786cf6b0d1925 Mon Sep 17 00:00:00 2001 From: Szymon Nowak Date: Thu, 13 Aug 2009 21:18:43 +0200 Subject: Fix creation of has_many through records with custom primary_key option on belongs_to [#2990 state:resolved] --- .../has_many_through_associations_test.rb | 30 +++++++++++++++++++++- activerecord/test/models/author.rb | 1 + activerecord/test/models/categorization.rb | 1 + activerecord/test/schema/schema.rb | 1 + 4 files changed, 32 insertions(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 816b43ab9e..d237273464 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -21,7 +21,7 @@ require 'models/categorization' require 'models/category' class HasManyThroughAssociationsTest < ActiveRecord::TestCase - fixtures :posts, :readers, :people, :comments, :authors, + fixtures :posts, :readers, :people, :comments, :authors, :categories, :owners, :pets, :toys, :jobs, :references, :companies, :subscribers, :books, :subscriptions, :developers, :categorizations @@ -397,6 +397,34 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase assert_equal people(:susan).agents.map(&:agents).flatten, people(:susan).agents_of_agents end + def test_associate_existing_with_nonstandard_primary_key_on_belongs_to + Categorization.create(:author => authors(:mary), :named_category_name => categories(:general).name) + assert_equal categories(:general), authors(:mary).named_categories.first + end + + def test_collection_build_with_nonstandard_primary_key_on_belongs_to + author = authors(:mary) + category = author.named_categories.build(:name => "Primary") + author.save + assert Categorization.exists?(:author_id => author.id, :named_category_name => category.name) + assert author.named_categories(true).include?(category) + end + + def test_collection_create_with_nonstandard_primary_key_on_belongs_to + author = authors(:mary) + category = author.named_categories.create(:name => "Primary") + assert Categorization.exists?(:author_id => author.id, :named_category_name => category.name) + assert author.named_categories(true).include?(category) + end + + def test_collection_delete_with_nonstandard_primary_key_on_belongs_to + author = authors(:mary) + category = author.named_categories.create(:name => "Primary") + author.named_categories.delete(category) + assert !Categorization.exists?(:author_id => author.id, :named_category_name => category.name) + assert author.named_categories(true).empty? + end + def test_collection_singular_ids_getter_with_string_primary_keys book = books(:awdr) assert_equal 2, book.subscriber_ids.size diff --git a/activerecord/test/models/author.rb b/activerecord/test/models/author.rb index 244c5ac4f5..83a6f5d926 100644 --- a/activerecord/test/models/author.rb +++ b/activerecord/test/models/author.rb @@ -78,6 +78,7 @@ class Author < ActiveRecord::Base has_many :categorizations has_many :categories, :through => :categorizations + has_many :named_categories, :through => :categorizations has_many :special_categorizations has_many :special_categories, :through => :special_categorizations, :source => :category diff --git a/activerecord/test/models/categorization.rb b/activerecord/test/models/categorization.rb index fdb0a11540..45f50e4af3 100644 --- a/activerecord/test/models/categorization.rb +++ b/activerecord/test/models/categorization.rb @@ -1,6 +1,7 @@ class Categorization < ActiveRecord::Base belongs_to :post belongs_to :category + belongs_to :named_category, :class_name => 'Category', :foreign_key => :named_category_name, :primary_key => :name belongs_to :author belongs_to :author_using_custom_pk, :class_name => 'Author', :foreign_key => :author_id, :primary_key => :author_address_extra_id diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 99761a4160..3dea7e1492 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -110,6 +110,7 @@ ActiveRecord::Schema.define do create_table :categorizations, :force => true do |t| t.column :category_id, :integer + t.string :named_category_name t.column :post_id, :integer t.column :author_id, :integer t.column :special, :boolean -- cgit v1.2.3 From 030480ac1f4fbf8bf74a0d9298544426caf26894 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20=C5=81omnicki?= Date: Sun, 12 Dec 2010 01:37:56 +0100 Subject: Fix behaviour of foo.has_many_through_association.select('custom select') [#6089 state:resolved] --- .../test/cases/associations/has_many_through_associations_test.rb | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index d237273464..6b71e73718 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -514,4 +514,9 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase assert_equal [posts(:eager_other)], posts end + + def test_select_chosen_fields_only + author = authors(:david) + assert_equal ['body'], author.comments.select('comments.body').first.attributes.keys + end end -- cgit v1.2.3 From ff7bde62c857ec94f45a5be3bc76468deb8b0b3a Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Wed, 22 Dec 2010 00:19:59 +0000 Subject: When a has_many association is not :uniq, appending the same record multiple times should append it to the @target multiple times [#5964 state:resolved] --- .../cases/associations/has_many_through_associations_test.rb | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 6b71e73718..dfb3292502 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -45,6 +45,16 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase assert posts(:thinking).reload.people(true).include?(people(:david)) end + def test_associate_existing_record_twice_should_add_to_target_twice + post = posts(:thinking) + person = people(:david) + + assert_difference 'post.people.to_a.count', 2 do + post.people << person + post.people << person + end + end + def test_associating_new assert_queries(1) { posts(:thinking) } new_person = nil # so block binding catches it -- cgit v1.2.3 From 4e13625818579551c01640cb405a8c22a3bd0e68 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Wed, 22 Dec 2010 10:11:27 +0000 Subject: Test demonstrating problem with foo.association_ids where it's a has_many :through with :conditions, with a belongs_to as the source reflection --- .../test/cases/associations/has_many_through_associations_test.rb | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index dfb3292502..ad67886202 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -529,4 +529,8 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase author = authors(:david) assert_equal ['body'], author.comments.select('comments.body').first.attributes.keys end + + def test_get_has_many_through_belongs_to_ids_with_conditions + assert_equal [categories(:general).id], authors(:mary).categories_like_general_ids + end end -- cgit v1.2.3 From 1619c2435b2b9c821b2b0dcab9624dbb6b23eaaa Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Wed, 22 Dec 2010 10:13:21 +0000 Subject: Revert "Optimize _ids for hm:t with belongs_to source". The optimisation has too many edge cases, such as when the reflection, source reflection, or through reflection has conditions, orders, etc. [#6153 state:resolved] This reverts commit 373b053dc8b99dac1abc3879a17a2bf8c30302b5. Conflicts: activerecord/lib/active_record/associations.rb --- .../test/cases/associations/has_many_through_associations_test.rb | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index ad67886202..a244d310c8 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -334,12 +334,8 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase assert_equal 2, people(:michael).jobs.size end - def test_get_ids_for_belongs_to_source - assert_sql(/DISTINCT/) { assert_equal [posts(:welcome).id, posts(:authorless).id].sort, people(:michael).post_ids.sort } - end - - def test_get_ids_for_has_many_source - assert_equal [comments(:eager_other_comment1).id], authors(:mary).comment_ids + def test_get_ids + assert_equal [posts(:welcome).id, posts(:authorless).id].sort, people(:michael).post_ids.sort end def test_get_ids_for_loaded_associations -- cgit v1.2.3 From 3f17ed407c5d61bc01fd59776205486c2350f36e Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Wed, 22 Dec 2010 11:45:37 +0000 Subject: Test to verify that #2189 (count with has_many :through and a named_scope) is fixed --- .../test/cases/associations/has_many_through_associations_test.rb | 5 +++++ activerecord/test/models/category.rb | 2 ++ 2 files changed, 7 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index a244d310c8..a417345780 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -529,4 +529,9 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase def test_get_has_many_through_belongs_to_ids_with_conditions assert_equal [categories(:general).id], authors(:mary).categories_like_general_ids end + + def test_count_has_many_through_with_named_scope + assert_equal 2, authors(:mary).categories.count + assert_equal 1, authors(:mary).categories.general.count + end end diff --git a/activerecord/test/models/category.rb b/activerecord/test/models/category.rb index 48415846dd..06908ea85e 100644 --- a/activerecord/test/models/category.rb +++ b/activerecord/test/models/category.rb @@ -23,6 +23,8 @@ class Category < ActiveRecord::Base has_many :categorizations has_many :authors, :through => :categorizations, :select => 'authors.*, categorizations.post_id' + + scope :general, :conditions => { :name => 'General' } end class SpecialCategory < Category -- cgit v1.2.3 From 2d9626fc74c2d57f90c856c37e5967bbe6651bd8 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Wed, 22 Dec 2010 20:57:41 +0000 Subject: Improved strategy for updating a belongs_to association when the foreign key changes. Rather than resetting each affected association when the foreign key changes, we should lazily check for 'staleness' (where fk does not match target id) when the association is accessed. --- activerecord/test/cases/nested_attributes_test.rb | 5 +++-- activerecord/test/cases/reflection_test.rb | 2 ++ 2 files changed, 5 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index ffcc7a081a..7d9b1104cd 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -298,7 +298,7 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase def test_should_create_new_model_when_nothing_is_there_and_update_only_is_true @ship.delete - + @pirate.reload.update_attributes(:update_only_ship_attributes => { :name => 'Mayflower' }) assert_not_nil @pirate.ship @@ -411,6 +411,7 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase def test_should_modify_an_existing_record_if_there_is_a_matching_composite_id @pirate.stubs(:id).returns('ABC1X') + @ship.stubs(:pirate_id).returns(@pirate.id) # prevents pirate from being reloaded due to non-matching foreign key @ship.pirate_attributes = { :id => @pirate.id, :catchphrase => 'Arr' } assert_equal 'Arr', @ship.pirate.catchphrase @@ -451,7 +452,7 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase def test_should_not_destroy_the_associated_model_until_the_parent_is_saved pirate = @ship.pirate - + @ship.attributes = { :pirate_attributes => { :id => pirate.id, '_destroy' => true } } assert_nothing_raised(ActiveRecord::RecordNotFound) { Pirate.find(pirate.id) } @ship.save diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index 1e205714a7..901c12b26c 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -7,6 +7,7 @@ require 'models/subscriber' require 'models/ship' require 'models/pirate' require 'models/price_estimate' +require 'models/tagging' class ReflectionTest < ActiveRecord::TestCase include ActiveRecord::Reflection @@ -194,6 +195,7 @@ class ReflectionTest < ActiveRecord::TestCase def test_association_primary_key assert_equal "id", Author.reflect_on_association(:posts).association_primary_key.to_s assert_equal "name", Author.reflect_on_association(:essay).association_primary_key.to_s + assert_equal "id", Tagging.reflect_on_association(:taggable).association_primary_key.to_s end def test_active_record_primary_key -- cgit v1.2.3 From 1c07b84df95e932d50376c1d0a13585b2e2ef868 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Thu, 23 Dec 2010 13:36:25 +0000 Subject: If a has_many goes :through a belongs_to, and the foreign key of the belongs_to changes, then the has_many should be considered stale. --- .../associations/belongs_to_associations_test.rb | 60 +++++++++++++--------- .../has_many_through_associations_test.rb | 16 ++++++ .../has_one_through_associations_test.rb | 15 ++++++ activerecord/test/fixtures/dashboards.yml | 5 +- activerecord/test/fixtures/members.yml | 2 + activerecord/test/fixtures/memberships.yml | 6 +-- activerecord/test/fixtures/speedometers.yml | 6 ++- activerecord/test/fixtures/sponsors.yml | 9 ++-- 8 files changed, 88 insertions(+), 31 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index 1820f95261..cdde9a80d3 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -17,7 +17,7 @@ require 'models/essay' class BelongsToAssociationsTest < ActiveRecord::TestCase fixtures :accounts, :companies, :developers, :projects, :topics, :developers_projects, :computers, :authors, :author_addresses, - :posts, :tags, :taggings, :comments + :posts, :tags, :taggings, :comments, :sponsors, :members def test_belongs_to Client.find(3).firm.name @@ -488,39 +488,53 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase end def test_reassigning_the_parent_id_updates_the_object - original_parent = Firm.create! :name => "original" - updated_parent = Firm.create! :name => "updated" + client = companies(:second_client) - client = Client.new("client_of" => original_parent.id) - assert_equal original_parent, client.firm - assert_equal original_parent, client.firm_with_condition - assert_equal original_parent, client.firm_with_other_name + client.firm + client.firm_with_condition + firm_proxy = client.send(:association_instance_get, :firm) + firm_with_condition_proxy = client.send(:association_instance_get, :firm_with_condition) - client.client_of = updated_parent.id - assert_equal updated_parent, client.firm - assert_equal updated_parent, client.firm_with_condition - assert_equal updated_parent, client.firm_with_other_name + assert !firm_proxy.stale_target? + assert !firm_with_condition_proxy.stale_target? + assert_equal companies(:first_firm), client.firm + assert_equal companies(:first_firm), client.firm_with_condition + + client.client_of = companies(:another_firm).id + + assert firm_proxy.stale_target? + assert firm_with_condition_proxy.stale_target? + assert_equal companies(:another_firm), client.firm + assert_equal companies(:another_firm), client.firm_with_condition end def test_polymorphic_reassignment_of_associated_id_updates_the_object - member1 = Member.create! - member2 = Member.create! + sponsor = sponsors(:moustache_club_sponsor_for_groucho) + + sponsor.sponsorable + proxy = sponsor.send(:association_instance_get, :sponsorable) + + assert !proxy.stale_target? + assert_equal members(:groucho), sponsor.sponsorable - sponsor = Sponsor.new("sponsorable_type" => "Member", "sponsorable_id" => member1.id) - assert_equal member1, sponsor.sponsorable + sponsor.sponsorable_id = members(:some_other_guy).id - sponsor.sponsorable_id = member2.id - assert_equal member2, sponsor.sponsorable + assert proxy.stale_target? + assert_equal members(:some_other_guy), sponsor.sponsorable end def test_polymorphic_reassignment_of_associated_type_updates_the_object - member1 = Member.create! + sponsor = sponsors(:moustache_club_sponsor_for_groucho) - sponsor = Sponsor.new("sponsorable_type" => "Member", "sponsorable_id" => member1.id) - assert_equal member1, sponsor.sponsorable + sponsor.sponsorable + proxy = sponsor.send(:association_instance_get, :sponsorable) - sponsor.sponsorable_type = "Firm" - assert_not_equal member1, sponsor.sponsorable - end + assert !proxy.stale_target? + assert_equal members(:groucho), sponsor.sponsorable + + sponsor.sponsorable_type = 'Firm' + assert proxy.stale_target? + assert_equal companies(:first_firm), sponsor.sponsorable + end end diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index a417345780..e98d178ff5 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -19,6 +19,7 @@ require 'models/book' require 'models/subscription' require 'models/categorization' require 'models/category' +require 'models/essay' class HasManyThroughAssociationsTest < ActiveRecord::TestCase fixtures :posts, :readers, :people, :comments, :authors, :categories, @@ -534,4 +535,19 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase assert_equal 2, authors(:mary).categories.count assert_equal 1, authors(:mary).categories.general.count end + + def test_has_many_through_belongs_to_should_update_when_the_through_foreign_key_changes + post = posts(:eager_other) + + post.author_categorizations + proxy = post.send(:association_instance_get, :author_categorizations) + + assert !proxy.stale_target? + assert_equal authors(:mary).categorizations.sort_by(&:id), post.author_categorizations.sort_by(&:id) + + post.author_id = authors(:david).id + + assert proxy.stale_target? + assert_equal authors(:david).categorizations.sort_by(&:id), post.author_categorizations.sort_by(&:id) + end end diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb index f6365e0216..7d55d909a7 100644 --- a/activerecord/test/cases/associations/has_one_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb @@ -251,4 +251,19 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase members(:groucho).club_through_many end end + + def test_has_one_through_belongs_to_should_update_when_the_through_foreign_key_changes + minivan = minivans(:cool_first) + + minivan.dashboard + proxy = minivan.send(:association_instance_get, :dashboard) + + assert !proxy.stale_target? + assert_equal dashboards(:cool_first), minivan.dashboard + + minivan.speedometer_id = speedometers(:second).id + + assert proxy.stale_target? + assert_equal dashboards(:second), minivan.dashboard + end end diff --git a/activerecord/test/fixtures/dashboards.yml b/activerecord/test/fixtures/dashboards.yml index e75bf46e6c..a4c7e0d309 100644 --- a/activerecord/test/fixtures/dashboards.yml +++ b/activerecord/test/fixtures/dashboards.yml @@ -1,3 +1,6 @@ cool_first: dashboard_id: d1 - name: my_dashboard \ No newline at end of file + name: my_dashboard +second: + dashboard_id: d2 + name: second diff --git a/activerecord/test/fixtures/members.yml b/activerecord/test/fixtures/members.yml index 6db945e61d..824840b7e5 100644 --- a/activerecord/test/fixtures/members.yml +++ b/activerecord/test/fixtures/members.yml @@ -1,6 +1,8 @@ groucho: + id: 1 name: Groucho Marx member_type_id: 1 some_other_guy: + id: 2 name: Englebert Humperdink member_type_id: 2 diff --git a/activerecord/test/fixtures/memberships.yml b/activerecord/test/fixtures/memberships.yml index b9722dbc8a..eed8b22af8 100644 --- a/activerecord/test/fixtures/memberships.yml +++ b/activerecord/test/fixtures/memberships.yml @@ -1,20 +1,20 @@ membership_of_boring_club: joined_on: <%= 3.weeks.ago.to_s(:db) %> club: boring_club - member: groucho + member_id: 1 favourite: false type: CurrentMembership membership_of_favourite_club: joined_on: <%= 3.weeks.ago.to_s(:db) %> club: moustache_club - member: groucho + member_id: 1 favourite: true type: Membership other_guys_membership: joined_on: <%= 4.weeks.ago.to_s(:db) %> club: boring_club - member: some_other_guy + member_id: 2 favourite: false type: CurrentMembership diff --git a/activerecord/test/fixtures/speedometers.yml b/activerecord/test/fixtures/speedometers.yml index 6a471aba0a..e12398f0c4 100644 --- a/activerecord/test/fixtures/speedometers.yml +++ b/activerecord/test/fixtures/speedometers.yml @@ -1,4 +1,8 @@ cool_first: speedometer_id: s1 name: my_speedometer - dashboard_id: d1 \ No newline at end of file + dashboard_id: d1 +second: + speedometer_id: s2 + name: second + dashboard_id: d2 diff --git a/activerecord/test/fixtures/sponsors.yml b/activerecord/test/fixtures/sponsors.yml index 42df8957d1..bfc6b238b1 100644 --- a/activerecord/test/fixtures/sponsors.yml +++ b/activerecord/test/fixtures/sponsors.yml @@ -1,9 +1,12 @@ moustache_club_sponsor_for_groucho: sponsor_club: moustache_club - sponsorable: groucho (Member) + sponsorable_id: 1 + sponsorable_type: Member boring_club_sponsor_for_groucho: sponsor_club: boring_club - sponsorable: some_other_guy (Member) + sponsorable_id: 2 + sponsorable_type: Member crazy_club_sponsor_for_groucho: sponsor_club: crazy_club - sponsorable: some_other_guy (Member) \ No newline at end of file + sponsorable_id: 2 + sponsorable_type: Member -- cgit v1.2.3 From fb3a8c51b4028e8d122fdbb783d73d0ed37ca168 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Thu, 23 Dec 2010 14:19:08 +0000 Subject: Raise an error for associations which try to go :through a polymorphic association [#6212 state:resolved] --- activerecord/test/cases/associations/join_model_test.rb | 11 ++++++++--- activerecord/test/models/tagging.rb | 3 ++- 2 files changed, 10 insertions(+), 4 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb index 58542bc939..263c90097f 100644 --- a/activerecord/test/cases/associations/join_model_test.rb +++ b/activerecord/test/cases/associations/join_model_test.rb @@ -340,11 +340,16 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase end def test_has_many_polymorphic - assert_raise ActiveRecord::HasManyThroughAssociationPolymorphicError do - assert_equal posts(:welcome, :thinking), tags(:general).taggables + assert_raise ActiveRecord::HasManyThroughAssociationPolymorphicSourceError do + tags(:general).taggables end + + assert_raise ActiveRecord::HasManyThroughAssociationPolymorphicThroughError do + taggings(:welcome_general).things + end + assert_raise ActiveRecord::EagerLoadPolymorphicError do - assert_equal posts(:welcome, :thinking), tags(:general).taggings.find(:all, :include => :taggable, :conditions => 'bogus_table.column = 1') + tags(:general).taggings.find(:all, :include => :taggable, :conditions => 'bogus_table.column = 1') end end diff --git a/activerecord/test/models/tagging.rb b/activerecord/test/models/tagging.rb index a1fa1a9750..33ffc623d7 100644 --- a/activerecord/test/models/tagging.rb +++ b/activerecord/test/models/tagging.rb @@ -7,4 +7,5 @@ class Tagging < ActiveRecord::Base belongs_to :super_tag, :class_name => 'Tag', :foreign_key => 'super_tag_id' belongs_to :invalid_tag, :class_name => 'Tag', :foreign_key => 'tag_id' belongs_to :taggable, :polymorphic => true, :counter_cache => true -end \ No newline at end of file + has_many :things, :through => :taggable +end -- cgit v1.2.3 From 6974c595fd480dc0ae3311ef60920fa87c5ff9d0 Mon Sep 17 00:00:00 2001 From: oleg dashevskii Date: Thu, 26 Aug 2010 11:22:27 +0700 Subject: Verify that there is no unwanted implicit readonly set on Model.has_many_through.find(id) [#5442 state:resolved] --- activerecord/test/cases/readonly_test.rb | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/readonly_test.rb b/activerecord/test/cases/readonly_test.rb index 98011f40a4..a1eb96ef09 100644 --- a/activerecord/test/cases/readonly_test.rb +++ b/activerecord/test/cases/readonly_test.rb @@ -12,7 +12,7 @@ def Project.foo() find :first end class ReadOnlyTest < ActiveRecord::TestCase - fixtures :posts, :comments, :developers, :projects, :developers_projects + fixtures :posts, :comments, :developers, :projects, :developers_projects, :people, :readers def test_cant_save_readonly_record dev = Developer.find(1) @@ -71,6 +71,18 @@ class ReadOnlyTest < ActiveRecord::TestCase assert !people.any?(&:readonly?) end + def test_has_many_with_through_is_not_implicitly_marked_readonly_while_finding_by_id + assert !posts(:welcome).people.find(1).readonly? + end + + def test_has_many_with_through_is_not_implicitly_marked_readonly_while_finding_first + assert !posts(:welcome).people.first.readonly? + end + + def test_has_many_with_through_is_not_implicitly_marked_readonly_while_finding_last + assert !posts(:welcome).people.last.readonly? + end + def test_readonly_scoping Post.send(:with_scope, :find => { :conditions => '1=1' }) do assert !Post.find(1).readonly? -- cgit v1.2.3 From ec13305b21d7146417b17a2cdf976bbc5cac2189 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 24 Dec 2010 22:15:41 -0700 Subject: stop redifining methods on every call to set_primary_key --- activerecord/test/cases/base_test.rb | 12 ++++++++---- activerecord/test/cases/inheritance_test.rb | 4 ++++ 2 files changed, 12 insertions(+), 4 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index e186b2aea7..09ef04a656 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -1073,10 +1073,14 @@ class BasicsTest < ActiveRecord::TestCase end def test_define_attr_method_with_block - k = Class.new( ActiveRecord::Base ) - k.primary_key = "id" - k.send(:define_attr_method, :primary_key) { "sys_" + original_primary_key } - assert_equal "sys_id", k.primary_key + k = Class.new( ActiveRecord::Base ) do + class << self + attr_accessor :foo_key + end + end + k.foo_key = "id" + k.send(:define_attr_method, :foo_key) { "sys_" + original_foo_key } + assert_equal "sys_id", k.foo_key end def test_set_table_name_with_value diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb index c3da9cdf53..6abbe45492 100644 --- a/activerecord/test/cases/inheritance_test.rb +++ b/activerecord/test/cases/inheritance_test.rb @@ -219,6 +219,10 @@ class InheritanceTest < ActiveRecord::TestCase switch_to_default_inheritance_column end + def test_inherits_custom_primary_key + assert_equal Subscriber.primary_key, SpecialSubscriber.primary_key + end + def test_inheritance_without_mapping assert_kind_of SpecialSubscriber, SpecialSubscriber.find("webster132") assert_nothing_raised { s = SpecialSubscriber.new("name" => "And breaaaaathe!"); s.id = 'roger'; s.save } -- cgit v1.2.3 From a6fe244e9b05c60aac88842a38fb2b6285d5571b Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Sat, 25 Dec 2010 15:23:45 -0700 Subject: take more advantage of arel sql compiler --- activerecord/test/cases/inheritance_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb index 6abbe45492..9fac9373eb 100644 --- a/activerecord/test/cases/inheritance_test.rb +++ b/activerecord/test/cases/inheritance_test.rb @@ -208,7 +208,7 @@ class InheritanceTest < ActiveRecord::TestCase def test_eager_load_belongs_to_primary_key_quoting con = Account.connection - assert_sql(/\(#{con.quote_table_name('companies')}.#{con.quote_column_name('id')} = 1\)/) do + assert_sql(/#{con.quote_table_name('companies')}.#{con.quote_column_name('id')} = 1/) do Account.find(1, :include => :firm) end end -- cgit v1.2.3 From 5b918bb97cb1801945ef778508a3738da98012c5 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Sat, 25 Dec 2010 16:19:59 -0700 Subject: using arel to compile sql statements --- activerecord/test/cases/finder_test.rb | 2 +- activerecord/test/fixtures/companies.yml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index 31e4981a1d..c35590b84b 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -982,7 +982,7 @@ class FinderTest < ActiveRecord::TestCase def test_select_rows assert_equal( - [["1", nil, nil, "37signals"], + [["1", "1", nil, "37signals"], ["2", "1", "2", "Summit"], ["3", "1", "1", "Microsoft"]], Company.connection.select_rows("SELECT id, firm_id, client_of, name FROM companies WHERE id IN (1,2,3) ORDER BY id").map! {|i| i.map! {|j| j.to_s unless j.nil?}}) diff --git a/activerecord/test/fixtures/companies.yml b/activerecord/test/fixtures/companies.yml index ffaa097686..30b73d8e84 100644 --- a/activerecord/test/fixtures/companies.yml +++ b/activerecord/test/fixtures/companies.yml @@ -9,6 +9,7 @@ first_client: first_firm: id: 1 + firm_id: 1 type: Firm name: 37signals ruby_type: Firm -- cgit v1.2.3 From f2230c06edf9c1ca72892bbe00e816be1dafa840 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Fri, 24 Dec 2010 00:14:46 +0000 Subject: Fix dodgy tests which were effectively asserting nil == nil --- activerecord/test/cases/associations/eager_test.rb | 6 +++--- activerecord/test/fixtures/companies.yml | 1 + 2 files changed, 4 insertions(+), 3 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index 6efb0d57e4..ad7eb6e4e6 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -886,15 +886,15 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_preload_has_one_using_primary_key - expected = Firm.find(:first).account_using_primary_key - firm = Firm.find :first, :include => :account_using_primary_key + expected = accounts(:signals37) + firm = Firm.find :first, :include => :account_using_primary_key, :order => 'companies.id' assert_no_queries do assert_equal expected, firm.account_using_primary_key end end def test_include_has_one_using_primary_key - expected = Firm.find(1).account_using_primary_key + expected = accounts(:signals37) firm = Firm.find(:all, :include => :account_using_primary_key, :order => 'accounts.id').detect {|f| f.id == 1} assert_no_queries do assert_equal expected, firm.account_using_primary_key diff --git a/activerecord/test/fixtures/companies.yml b/activerecord/test/fixtures/companies.yml index 30b73d8e84..c75bc5dad3 100644 --- a/activerecord/test/fixtures/companies.yml +++ b/activerecord/test/fixtures/companies.yml @@ -13,6 +13,7 @@ first_firm: type: Firm name: 37signals ruby_type: Firm + firm_id: 1 second_client: id: 3 -- cgit v1.2.3 From e8ada11aac28f0850f0e485acacf34e7eb81aa19 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Fri, 24 Dec 2010 00:29:04 +0000 Subject: Associations: DRY up the code which is generating conditions, and make it all use arel rather than SQL strings --- activerecord/test/fixtures/companies.yml | 1 - 1 file changed, 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/fixtures/companies.yml b/activerecord/test/fixtures/companies.yml index c75bc5dad3..a982d3921d 100644 --- a/activerecord/test/fixtures/companies.yml +++ b/activerecord/test/fixtures/companies.yml @@ -9,7 +9,6 @@ first_client: first_firm: id: 1 - firm_id: 1 type: Firm name: 37signals ruby_type: Firm -- cgit v1.2.3 From 7e91ad3f89ba134d863072db8db06ece6ec3ef19 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Sun, 26 Dec 2010 19:56:18 -0700 Subject: stop calling deprecated apis --- activerecord/test/cases/method_scoping_test.rb | 8 ++++---- activerecord/test/cases/relation_scoping_test.rb | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/method_scoping_test.rb b/activerecord/test/cases/method_scoping_test.rb index 0ffd0e2ab3..e3ba65b4fa 100644 --- a/activerecord/test/cases/method_scoping_test.rb +++ b/activerecord/test/cases/method_scoping_test.rb @@ -14,7 +14,7 @@ class MethodScopingTest < ActiveRecord::TestCase def test_set_conditions Developer.send(:with_scope, :find => { :conditions => 'just a test...' }) do - assert_equal '(just a test...)', Developer.scoped.arel.send(:where_clauses).join(' AND ') + assert_match '(just a test...)', Developer.scoped.arel.to_sql end end @@ -275,7 +275,7 @@ class NestedScopingTest < ActiveRecord::TestCase Developer.send(:with_scope, :find => { :conditions => 'salary = 80000' }) do Developer.send(:with_scope, :find => { :limit => 10 }) do devs = Developer.scoped - assert_equal '(salary = 80000)', devs.arel.send(:where_clauses).join(' AND ') + assert_match '(salary = 80000)', devs.arel.to_sql assert_equal 10, devs.taken end end @@ -309,7 +309,7 @@ class NestedScopingTest < ActiveRecord::TestCase Developer.send(:with_scope, :find => { :conditions => "name = 'David'" }) do Developer.send(:with_scope, :find => { :conditions => 'salary = 80000' }) do devs = Developer.scoped - assert_equal "(name = 'David') AND (salary = 80000)", devs.arel.send(:where_clauses).join(' AND ') + assert_match "(name = 'David') AND (salary = 80000)", devs.arel.to_sql assert_equal(1, Developer.count) end Developer.send(:with_scope, :find => { :conditions => "name = 'Maiha'" }) do @@ -322,7 +322,7 @@ class NestedScopingTest < ActiveRecord::TestCase Developer.send(:with_scope, :find => { :conditions => 'salary = 80000', :limit => 10 }) do Developer.send(:with_scope, :find => { :conditions => "name = 'David'" }) do devs = Developer.scoped - assert_equal "(salary = 80000) AND (name = 'David')", devs.arel.send(:where_clauses).join(' AND ') + assert_match "(salary = 80000) AND (name = 'David')", devs.arel.to_sql assert_equal 10, devs.taken end end diff --git a/activerecord/test/cases/relation_scoping_test.rb b/activerecord/test/cases/relation_scoping_test.rb index f113a9c516..e8672515fc 100644 --- a/activerecord/test/cases/relation_scoping_test.rb +++ b/activerecord/test/cases/relation_scoping_test.rb @@ -152,7 +152,7 @@ class NestedRelationScopingTest < ActiveRecord::TestCase Developer.where('salary = 80000').scoping do Developer.limit(10).scoping do devs = Developer.scoped - assert_equal '(salary = 80000)', devs.arel.send(:where_clauses).join(' AND ') + assert_match '(salary = 80000)', devs.arel.to_sql assert_equal 10, devs.taken end end -- cgit v1.2.3 From 304d38c0536dc32a8a1595ba34370ebf69a0d50d Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Tue, 28 Dec 2010 00:45:35 -0200 Subject: Allow primary_key to be an attribute when the model is a new record --- activerecord/test/cases/attribute_methods_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb index 8214815bde..e3cbae4a84 100644 --- a/activerecord/test/cases/attribute_methods_test.rb +++ b/activerecord/test/cases/attribute_methods_test.rb @@ -105,7 +105,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase def test_read_attributes_before_type_cast category = Category.new({:name=>"Test categoty", :type => nil}) - category_attrs = {"name"=>"Test categoty", "type" => nil, "categorizations_count" => nil} + category_attrs = {"name"=>"Test categoty", "id" => nil, "type" => nil, "categorizations_count" => nil} assert_equal category_attrs , category.attributes_before_type_cast end -- cgit v1.2.3 From fd1cf13f743ac7ba71f19dff6d8e22f5ac7bc603 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Wed, 29 Dec 2010 16:15:45 +0000 Subject: Make serialized fixtures work again --- activerecord/test/cases/base_test.rb | 2 +- activerecord/test/cases/fixtures_test.rb | 7 ++++++- activerecord/test/cases/quoting_test.rb | 4 ++-- activerecord/test/fixtures/traffic_lights.yml | 6 ++++++ activerecord/test/models/traffic_light.rb | 3 +++ 5 files changed, 18 insertions(+), 4 deletions(-) create mode 100644 activerecord/test/fixtures/traffic_lights.yml create mode 100644 activerecord/test/models/traffic_light.rb (limited to 'activerecord/test') diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 09ef04a656..594f3b80c6 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -703,7 +703,7 @@ class BasicsTest < ActiveRecord::TestCase duped_topic.reload # FIXME: I think this is poor behavior, and will fix it with #5686 - assert_equal({'a' => 'c'}.to_s, duped_topic.title) + assert_equal({'a' => 'c'}.to_yaml, duped_topic.title) end def test_dup_with_aggregate_of_same_name_as_attribute diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb index 9ce163a00f..864a7a2acc 100644 --- a/activerecord/test/cases/fixtures_test.rb +++ b/activerecord/test/cases/fixtures_test.rb @@ -13,6 +13,7 @@ require 'models/category' require 'models/parrot' require 'models/pirate' require 'models/treasure' +require 'models/traffic_light' require 'models/matey' require 'models/ship' require 'models/book' @@ -24,7 +25,7 @@ class FixturesTest < ActiveRecord::TestCase self.use_instantiated_fixtures = true self.use_transactional_fixtures = false - fixtures :topics, :developers, :accounts, :tasks, :categories, :funny_jokes, :binaries + fixtures :topics, :developers, :accounts, :tasks, :categories, :funny_jokes, :binaries, :traffic_lights FIXTURES = %w( accounts binaries companies customers developers developers_projects entrants @@ -204,6 +205,10 @@ class FixturesTest < ActiveRecord::TestCase data.freeze assert_equal data, @flowers.data end + + def test_serialized_fixtures + assert_equal ["Green", "Red", "Orange"], traffic_lights(:uk).state + end end if Account.connection.respond_to?(:reset_pk_sequence!) diff --git a/activerecord/test/cases/quoting_test.rb b/activerecord/test/cases/quoting_test.rb index 2ef5b5a800..b87fb51d97 100644 --- a/activerecord/test/cases/quoting_test.rb +++ b/activerecord/test/cases/quoting_test.rb @@ -154,13 +154,13 @@ module ActiveRecord end def test_crazy_object - crazy = Class.new { def to_s; 'lol' end }.new + crazy = Class.new { def to_yaml; 'lol' end }.new assert_equal "'lol'", @quoter.quote(crazy, nil) assert_equal "'lol'", @quoter.quote(crazy, Object.new) end def test_crazy_object_calls_quote_string - crazy = Class.new { def to_s; 'lo\l' end }.new + crazy = Class.new { def to_yaml; 'lo\l' end }.new assert_equal "'lo\\\\l'", @quoter.quote(crazy, nil) assert_equal "'lo\\\\l'", @quoter.quote(crazy, Object.new) end diff --git a/activerecord/test/fixtures/traffic_lights.yml b/activerecord/test/fixtures/traffic_lights.yml new file mode 100644 index 0000000000..6dabd53474 --- /dev/null +++ b/activerecord/test/fixtures/traffic_lights.yml @@ -0,0 +1,6 @@ +uk: + location: UK + state: + - Green + - Red + - Orange diff --git a/activerecord/test/models/traffic_light.rb b/activerecord/test/models/traffic_light.rb new file mode 100644 index 0000000000..228f3f7bd4 --- /dev/null +++ b/activerecord/test/models/traffic_light.rb @@ -0,0 +1,3 @@ +class TrafficLight < ActiveRecord::Base + serialize :state, Array +end -- cgit v1.2.3 From 573fd39e22b3d278457fa764c107095808b361fe Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Thu, 30 Dec 2010 18:41:53 +0000 Subject: Make sure Model#touch doesn't try to update non existing columns --- activerecord/test/models/task.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/models/task.rb b/activerecord/test/models/task.rb index ee0282c79b..e36989dd56 100644 --- a/activerecord/test/models/task.rb +++ b/activerecord/test/models/task.rb @@ -1,3 +1,5 @@ class Task < ActiveRecord::Base - + def updated_at + ending + end end -- cgit v1.2.3 From 38fbfa6390c449dfc9a3db2975e65bd0fd665b18 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Thu, 30 Dec 2010 20:41:02 +0000 Subject: Refactor configure_dependency_for_has_many to use AssociationCollection#delete_all. It was necessary to change test_before_destroy in lifecycle_test.rb so that it checks topic.replies.size *before* doing the destroy, as afterwards it will now (correctly) be 0. --- activerecord/test/cases/lifecycle_test.rb | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/lifecycle_test.rb b/activerecord/test/cases/lifecycle_test.rb index b8c3ffb9cb..0558deb71b 100644 --- a/activerecord/test/cases/lifecycle_test.rb +++ b/activerecord/test/cases/lifecycle_test.rb @@ -101,9 +101,10 @@ class LifecycleTest < ActiveRecord::TestCase fixtures :topics, :developers, :minimalistics def test_before_destroy - original_count = Topic.count - (topic_to_be_destroyed = Topic.find(1)).destroy - assert_equal original_count - (1 + topic_to_be_destroyed.replies.size), Topic.count + topic = Topic.find(1) + assert_difference 'Topic.count', -(1 + topic.replies.size) do + topic.destroy + end end def test_auto_observer -- cgit v1.2.3 From 2bf31868033c50d71d6d68c1ddad67147908adc4 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Thu, 30 Dec 2010 21:44:29 +0000 Subject: Verify that when has_many associated objects are destroyed via :dependent => :destroy, when the parent is destroyed, the callbacks are run --- activerecord/test/cases/associations/callbacks_test.rb | 9 +++++++++ activerecord/test/models/company.rb | 17 ++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/callbacks_test.rb b/activerecord/test/cases/associations/callbacks_test.rb index 6a30e2905b..2d0d4541b4 100644 --- a/activerecord/test/cases/associations/callbacks_test.rb +++ b/activerecord/test/cases/associations/callbacks_test.rb @@ -3,6 +3,7 @@ require 'models/post' require 'models/author' require 'models/project' require 'models/developer' +require 'models/company' class AssociationCallbacksTest < ActiveRecord::TestCase fixtures :posts, :authors, :projects, :developers @@ -81,6 +82,14 @@ class AssociationCallbacksTest < ActiveRecord::TestCase assert_equal callback_log, jack.post_log end + def test_has_many_callbacks_for_destroy_on_parent + firm = Firm.create! :name => "Firm" + client = firm.clients.create! :name => "Client" + firm.destroy + + assert_equal ["before_remove#{client.id}", "after_remove#{client.id}"], firm.log + end + def test_has_and_belongs_to_many_add_callback david = developers(:david) ar = projects(:active_record) diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb index ee5f77b613..7af4dfe2c9 100644 --- a/activerecord/test/models/company.rb +++ b/activerecord/test/models/company.rb @@ -38,7 +38,9 @@ end class Firm < Company has_many :clients, :order => "id", :dependent => :destroy, :counter_sql => "SELECT COUNT(*) FROM companies WHERE firm_id = 1 " + - "AND (#{QUOTED_TYPE} = 'Client' OR #{QUOTED_TYPE} = 'SpecialClient' OR #{QUOTED_TYPE} = 'VerySpecialClient' )" + "AND (#{QUOTED_TYPE} = 'Client' OR #{QUOTED_TYPE} = 'SpecialClient' OR #{QUOTED_TYPE} = 'VerySpecialClient' )", + :before_remove => :log_before_remove, + :after_remove => :log_after_remove has_many :unsorted_clients, :class_name => "Client" has_many :clients_sorted_desc, :class_name => "Client", :order => "id DESC" has_many :clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id" @@ -88,6 +90,19 @@ class Firm < Company has_one :unautosaved_account, :foreign_key => "firm_id", :class_name => 'Account', :autosave => false has_many :accounts has_many :unautosaved_accounts, :foreign_key => "firm_id", :class_name => 'Account', :autosave => false + + def log + @log ||= [] + end + + private + def log_before_remove(record) + log << "before_remove#{record.id}" + end + + def log_after_remove(record) + log << "after_remove#{record.id}" + end end class DependentFirm < Company -- cgit v1.2.3 From 62b084f80759300f10a4e5c4235bf1d13693a7d3 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Fri, 31 Dec 2010 10:43:42 +0000 Subject: Specify the STI type condition using SQL IN rather than a whole load of ORs. Required a fix to ActiveRecord::Relation#merge for properly merging create_with_value. This also fixes a situation where the type condition was appearing twice in the resultant SQL query. --- activerecord/test/cases/relation_scoping_test.rb | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/relation_scoping_test.rb b/activerecord/test/cases/relation_scoping_test.rb index e8672515fc..7c6899d438 100644 --- a/activerecord/test/cases/relation_scoping_test.rb +++ b/activerecord/test/cases/relation_scoping_test.rb @@ -485,4 +485,11 @@ class DefaultScopingTest < ActiveRecord::TestCase posts_offset_limit = Post.offset(2).limit(3) assert_equal posts_limit_offset, posts_offset_limit end + + def test_create_with_merge + aaron = (PoorDeveloperCalledJamis.create_with(:name => 'foo', :salary => 20) & + PoorDeveloperCalledJamis.create_with(:name => 'Aaron')).new + assert_equal 20, aaron.salary + assert_equal 'Aaron', aaron.name + end end -- cgit v1.2.3 From bea4065d3c8c8f845ddda45b3ec98e3fb308d913 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Fri, 31 Dec 2010 18:08:44 +0000 Subject: Refactor BelongsToAssociation to allow BelongsToPolymorphicAssociation to inherit from it --- .../associations/belongs_to_associations_test.rb | 42 ++++++++++++++++++---- 1 file changed, 36 insertions(+), 6 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index cdde9a80d3..6dcbbc7e34 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -198,16 +198,23 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase assert_equal 1, Post.find(p.id).comments.size end - def test_belongs_to_with_primary_key_counter_with_assigning_nil - debate = Topic.create("title" => "debate") - reply = Reply.create("title" => "blah!", "content" => "world around!", "parent_title" => "debate") + def test_belongs_to_with_primary_key_counter + debate = Topic.create("title" => "debate") + debate2 = Topic.create("title" => "debate2") + reply = Reply.create("title" => "blah!", "content" => "world around!", "parent_title" => "debate") + + assert_equal 1, debate.reload.replies_count + assert_equal 0, debate2.reload.replies_count + + reply.topic_with_primary_key = debate2 - assert_equal debate.title, reply.parent_title - assert_equal 1, Topic.find(debate.id).send(:read_attribute, "replies_count") + assert_equal 0, debate.reload.replies_count + assert_equal 1, debate2.reload.replies_count reply.topic_with_primary_key = nil - assert_equal 0, Topic.find(debate.id).send(:read_attribute, "replies_count") + assert_equal 0, debate.reload.replies_count + assert_equal 0, debate2.reload.replies_count end def test_belongs_to_counter_with_reassigning @@ -419,6 +426,18 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase assert_nil sponsor.sponsorable_id end + def test_assignment_updates_foreign_id_field_for_new_and_saved_records + client = Client.new + saved_firm = Firm.create :name => "Saved" + new_firm = Firm.new + + client.firm = saved_firm + assert_equal saved_firm.id, client.client_of + + client.firm = new_firm + assert_nil client.client_of + end + def test_polymorphic_assignment_with_primary_key_updates_foreign_id_field_for_new_and_saved_records essay = Essay.new saved_writer = Author.create(:name => "David") @@ -537,4 +556,15 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase assert proxy.stale_target? assert_equal companies(:first_firm), sponsor.sponsorable end + + def test_reloading_association_with_key_change + client = companies(:second_client) + firm = client.firm # note this is a proxy object + + client.firm = companies(:another_firm) + assert_equal companies(:another_firm), firm.reload + + client.client_of = companies(:first_firm).id + assert_equal companies(:first_firm), firm.reload + end end -- cgit v1.2.3 From 3c400627eb9cfac380d716ccf1182d61db4a45a6 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Fri, 31 Dec 2010 18:36:02 +0000 Subject: Support for :counter_cache on polymorphic belongs_to --- .../test/cases/associations/belongs_to_associations_test.rb | 12 ++++++++++++ activerecord/test/schema/schema.rb | 1 + 2 files changed, 13 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index 6dcbbc7e34..f97f89b6fe 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -567,4 +567,16 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase client.client_of = companies(:first_firm).id assert_equal companies(:first_firm), firm.reload end + + def test_polymorphic_counter_cache + tagging = taggings(:welcome_general) + post = posts(:welcome) + comment = comments(:greetings) + + assert_difference 'post.reload.taggings_count', -1 do + assert_difference 'comment.reload.taggings_count', +1 do + tagging.taggable = comment + end + end + end end diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 3dea7e1492..7f366b2c91 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -143,6 +143,7 @@ ActiveRecord::Schema.define do t.text :body, :null => false end t.string :type + t.integer :taggings_count, :default => 0 end create_table :companies, :force => true do |t| -- cgit v1.2.3 From 12675988813e82ac30f7c0e0008c12c4cf5d8cdc Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Fri, 31 Dec 2010 20:00:24 +0000 Subject: Rename AssociationReflection#primary_key_name to foreign_key, since the options key which it relates to is :foreign_key --- activerecord/test/cases/reflection_test.rb | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index 901c12b26c..e3db34520e 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -8,6 +8,8 @@ require 'models/ship' require 'models/pirate' require 'models/price_estimate' require 'models/tagging' +require 'models/author' +require 'models/post' class ReflectionTest < ActiveRecord::TestCase include ActiveRecord::Reflection @@ -127,11 +129,11 @@ class ReflectionTest < ActiveRecord::TestCase def test_belongs_to_inferred_foreign_key_from_assoc_name Company.belongs_to :foo - assert_equal "foo_id", Company.reflect_on_association(:foo).primary_key_name + assert_equal "foo_id", Company.reflect_on_association(:foo).foreign_key Company.belongs_to :bar, :class_name => "Xyzzy" - assert_equal "bar_id", Company.reflect_on_association(:bar).primary_key_name + assert_equal "bar_id", Company.reflect_on_association(:bar).foreign_key Company.belongs_to :baz, :class_name => "Xyzzy", :foreign_key => "xyzzy_id" - assert_equal "xyzzy_id", Company.reflect_on_association(:baz).primary_key_name + assert_equal "xyzzy_id", Company.reflect_on_association(:baz).foreign_key end def test_association_reflection_in_modules -- cgit v1.2.3 From febdf5a5a91ac04fad2c7996f7f55fa19f0ff7d7 Mon Sep 17 00:00:00 2001 From: "Robert Pankowecki (Gavdi)" Date: Fri, 31 Dec 2010 20:48:48 +0800 Subject: Added one more failing test for bug #6036 --- activerecord/test/cases/relations_test.rb | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 20bfafbc5e..ed6ea4db0a 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -27,6 +27,12 @@ class RelationTest < ActiveRecord::TestCase assert_equal van.id, Minivan.where(:minivan_id => van).to_a.first.minivan_id end + def test_do_not_double_quote_string_id_with_array + van = Minivan.last + assert van + assert_equal van, Minivan.where(:minivan_id => [van]).to_a.first + end + def test_bind_values relation = Post.scoped assert_equal [], relation.bind_values -- cgit v1.2.3 From 60cf65def805995bcca184c40b44bb01d86a48aa Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 3 Jan 2011 15:12:51 -0800 Subject: herp derpricating add_limit_offset! --- activerecord/test/cases/adapter_test.rb | 12 ------------ 1 file changed, 12 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/adapter_test.rb b/activerecord/test/cases/adapter_test.rb index 646aa88d80..49b2e945c3 100644 --- a/activerecord/test/cases/adapter_test.rb +++ b/activerecord/test/cases/adapter_test.rb @@ -141,16 +141,4 @@ class AdapterTest < ActiveRecord::TestCase end end end - - def test_add_limit_offset_should_sanitize_sql_injection_for_limit_without_comas - sql_inject = "1 select * from schema" - assert_no_match(/schema/, @connection.add_limit_offset!("", :limit=>sql_inject)) - assert_no_match(/schema/, @connection.add_limit_offset!("", :limit=>sql_inject, :offset=>7)) - end - - def test_add_limit_offset_should_sanitize_sql_injection_for_limit_with_comas - sql_inject = "1, 7 procedure help()" - assert_no_match(/procedure/, @connection.add_limit_offset!("", :limit=>sql_inject)) - assert_no_match(/procedure/, @connection.add_limit_offset!("", :limit=>sql_inject, :offset=>7)) - end end -- cgit v1.2.3 From 16065b4f19b77111b7fec343969bcf98635e7e27 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sat, 1 Jan 2011 18:18:54 +0000 Subject: Some basic tests for the :foreign_type option on belongs_to, which was previously completely untested. --- .../associations/belongs_to_associations_test.rb | 19 +++++++++++++++++++ activerecord/test/cases/associations/eager_test.rb | 13 ++++++++++++- activerecord/test/models/sponsor.rb | 3 ++- 3 files changed, 33 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index f97f89b6fe..f697fdf628 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -579,4 +579,23 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase end end end + + def test_polymorphic_with_custom_foreign_type + sponsor = sponsors(:moustache_club_sponsor_for_groucho) + groucho = members(:groucho) + other = members(:some_other_guy) + + assert_equal groucho, sponsor.sponsorable + assert_equal groucho, sponsor.thing + + sponsor.thing = other + + assert_equal other, sponsor.sponsorable + assert_equal other, sponsor.thing + + sponsor.sponsorable = groucho + + assert_equal groucho, sponsor.sponsorable + assert_equal groucho, sponsor.thing + end end diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index ad7eb6e4e6..19c69ed7bc 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -21,12 +21,13 @@ require 'models/member' require 'models/membership' require 'models/club' require 'models/categorization' +require 'models/sponsor' class EagerAssociationTest < ActiveRecord::TestCase fixtures :posts, :comments, :authors, :author_addresses, :categories, :categories_posts, :companies, :accounts, :tags, :taggings, :people, :readers, :categorizations, :owners, :pets, :author_favorites, :jobs, :references, :subscribers, :subscriptions, :books, - :developers, :projects, :developers_projects, :members, :memberships, :clubs + :developers, :projects, :developers_projects, :members, :memberships, :clubs, :sponsors def setup # preheat table existence caches @@ -913,4 +914,14 @@ class EagerAssociationTest < ActiveRecord::TestCase assert_equal 1, mary.unique_categorized_posts.length assert_equal 1, mary.unique_categorized_post_ids.length end + + def test_preloading_polymorphic_with_custom_foreign_type + sponsor = sponsors(:moustache_club_sponsor_for_groucho) + groucho = members(:groucho) + + sponsor = assert_queries(2) { + Sponsor.includes(:thing).where(:id => sponsor.id).first + } + assert_no_queries { assert_equal groucho, sponsor.thing } + end end diff --git a/activerecord/test/models/sponsor.rb b/activerecord/test/models/sponsor.rb index 50c2c2d76c..7e5a1dc38b 100644 --- a/activerecord/test/models/sponsor.rb +++ b/activerecord/test/models/sponsor.rb @@ -1,4 +1,5 @@ class Sponsor < ActiveRecord::Base belongs_to :sponsor_club, :class_name => "Club", :foreign_key => "club_id" belongs_to :sponsorable, :polymorphic => true -end \ No newline at end of file + belongs_to :thing, :polymorphic => true, :foreign_type => :sponsorable_type, :foreign_key => :sponsorable_id +end -- cgit v1.2.3 From c47f802d0e7b0156512f197887d6e9bda6d0f269 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sat, 1 Jan 2011 18:52:48 +0000 Subject: Have a proper AssociationReflection#foreign_type method rather than using options[:foreign_type] --- activerecord/test/cases/reflection_test.rb | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index e3db34520e..081e3cc861 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -10,6 +10,7 @@ require 'models/price_estimate' require 'models/tagging' require 'models/author' require 'models/post' +require 'models/sponsor' class ReflectionTest < ActiveRecord::TestCase include ActiveRecord::Reflection @@ -205,6 +206,11 @@ class ReflectionTest < ActiveRecord::TestCase assert_equal "name", Author.reflect_on_association(:essay).active_record_primary_key.to_s end + def test_foreign_type + assert_equal "sponsorable_type", Sponsor.reflect_on_association(:sponsorable).foreign_type.to_s + assert_equal "sponsorable_type", Sponsor.reflect_on_association(:thing).foreign_type.to_s + end + def test_collection_association assert Pirate.reflect_on_association(:birds).collection? assert Pirate.reflect_on_association(:parrots).collection? -- cgit v1.2.3 From a0be389d39b790e0625339251d2674b8250b16b1 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sun, 2 Jan 2011 14:28:53 +0000 Subject: Allow assignment on has_one :through where the owner is a new record [#5137 state:resolved] This required changing the code to keep the association proxy for a belongs_to around, despite its target being nil. Which in turn required various changes to the way that stale target checking is handled, in order to support various edge cases (loaded target is nil then foreign key added, foreign key is changed and then changed back, etc). A side effect is that the code is nicer and more succinct. Note that I am removing test_no_unexpected_aliasing since that is basically checking that the proxy for a belongs_to *does* change, which is the exact opposite of the intention of this commit. Also adding various tests for various edge cases and related things. Phew, long commit message! --- .../associations/belongs_to_associations_test.rb | 33 +++++++++------------- activerecord/test/cases/associations/eager_test.rb | 20 +++++++++++-- .../has_one_through_associations_test.rb | 22 +++++++++++++++ .../test/cases/autosave_association_test.rb | 7 +++++ activerecord/test/cases/nested_attributes_test.rb | 1 - activerecord/test/models/company.rb | 1 + 6 files changed, 61 insertions(+), 23 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index f697fdf628..38ee4ad4e0 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -88,19 +88,6 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase assert_not_nil citibank_result.instance_variable_get("@firm_with_primary_key_symbols") end - def test_no_unexpected_aliasing - first_firm = companies(:first_firm) - another_firm = companies(:another_firm) - - citibank = Account.create("credit_limit" => 10) - citibank.firm = first_firm - original_proxy = citibank.firm - citibank.firm = another_firm - - assert_equal first_firm.object_id, original_proxy.target.object_id - assert_equal another_firm.object_id, citibank.firm.target.object_id - end - def test_creating_the_belonging_object citibank = Account.create("credit_limit" => 10) apple = citibank.create_firm("name" => "Apple") @@ -318,13 +305,21 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase assert_equal Firm.find(:first, :order => "id"), c.firm_with_basic_id end - def test_forgetting_the_load_when_foreign_key_enters_late - c = Client.new - assert_nil c.firm_with_basic_id + def test_setting_foreign_key_after_nil_target_loaded + client = Client.new + client.firm_with_basic_id + client.firm_id = 1 - c.firm_id = 1 - # sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first - assert_equal Firm.find(:first, :order => "id"), c.firm_with_basic_id + assert_equal companies(:first_firm), client.firm_with_basic_id + end + + def test_polymorphic_setting_foreign_key_after_nil_target_loaded + sponsor = Sponsor.new + sponsor.sponsorable + sponsor.sponsorable_id = 1 + sponsor.sponsorable_type = "Member" + + assert_equal members(:groucho), sponsor.sponsorable end def test_field_name_same_as_foreign_key diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index 19c69ed7bc..2a9351507a 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -902,11 +902,25 @@ class EagerAssociationTest < ActiveRecord::TestCase end end - def test_preloading_empty_polymorphic_parent + def test_preloading_empty_belongs_to + c = Client.create!(:name => 'Foo', :client_of => Company.maximum(:id) + 1) + + client = assert_queries(2) { Client.preload(:firm).find(c.id) } + assert_no_queries { assert_nil client.firm } + end + + def test_preloading_empty_belongs_to_polymorphic t = Tagging.create!(:taggable_type => 'Post', :taggable_id => Post.maximum(:id) + 1, :tag => tags(:general)) - assert_queries(2) { @tagging = Tagging.preload(:taggable).find(t.id) } - assert_no_queries { assert ! @tagging.taggable } + tagging = assert_queries(2) { Tagging.preload(:taggable).find(t.id) } + assert_no_queries { assert_nil tagging.taggable } + end + + def test_preloading_through_empty_belongs_to + c = Client.create!(:name => 'Foo', :client_of => Company.maximum(:id) + 1) + + client = assert_queries(2) { Client.preload(:accounts).find(c.id) } + assert_no_queries { assert client.accounts.empty? } end def test_preloading_has_many_through_with_uniq diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb index 7d55d909a7..0afbef5c87 100644 --- a/activerecord/test/cases/associations/has_one_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb @@ -266,4 +266,26 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase assert proxy.stale_target? assert_equal dashboards(:second), minivan.dashboard end + + def test_has_one_through_belongs_to_setting_belongs_to_foreign_key_after_nil_target_loaded + minivan = Minivan.new + + minivan.dashboard + proxy = minivan.send(:association_instance_get, :dashboard) + + minivan.speedometer_id = speedometers(:second).id + + assert proxy.stale_target? + assert_equal dashboards(:second), minivan.dashboard + end + + def test_assigning_has_one_through_belongs_to_with_new_record_owner + minivan = Minivan.new + dashboard = dashboards(:cool_first) + + minivan.dashboard = dashboard + + assert_equal dashboard, minivan.dashboard + assert_equal dashboard, minivan.speedometer.dashboard + end end diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index 27aee400f9..71fd3fd836 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -340,6 +340,13 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test tags(:misc).create_tagging(:taggable => posts(:thinking)) assert_equal num_tagging + 1, Tagging.count end + + def test_build_and_then_save_parent_should_not_reload_target + client = Client.find(:first) + apple = client.build_firm(:name => "Apple") + client.save! + assert_no_queries { assert_equal apple, client.firm } + end end class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCase diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index 7d9b1104cd..d290afc1dd 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -411,7 +411,6 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase def test_should_modify_an_existing_record_if_there_is_a_matching_composite_id @pirate.stubs(:id).returns('ABC1X') - @ship.stubs(:pirate_id).returns(@pirate.id) # prevents pirate from being reloaded due to non-matching foreign key @ship.pirate_attributes = { :id => @pirate.id, :catchphrase => 'Arr' } assert_equal 'Arr', @ship.pirate.catchphrase diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb index 7af4dfe2c9..d08e593db1 100644 --- a/activerecord/test/models/company.rb +++ b/activerecord/test/models/company.rb @@ -124,6 +124,7 @@ class Client < Company belongs_to :firm_with_primary_key, :class_name => "Firm", :primary_key => "name", :foreign_key => "firm_name" belongs_to :firm_with_primary_key_symbols, :class_name => "Firm", :primary_key => :name, :foreign_key => :firm_name belongs_to :readonly_firm, :class_name => "Firm", :foreign_key => "firm_id", :readonly => true + has_many :accounts, :through => :firm # Record destruction so we can test whether firm.clients.clear has # is calling client.destroy, deleting from the database, or setting -- cgit v1.2.3 From d6289aadce1b8fa93e799500e52f92ce8d159d6f Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sun, 2 Jan 2011 17:56:26 +0000 Subject: Fix test_any in relations_test.rb, which was failing when relations_test.rb is run on its own (it passes when the entire suite is run). This is a hacky fix for a problem I didn't quite get to the bottom of, so I'd welcome a better solution... --- activerecord/test/cases/relations_test.rb | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index ed6ea4db0a..cd774ce343 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -640,6 +640,14 @@ class RelationTest < ActiveRecord::TestCase def test_any posts = Post.scoped + # This test was failing when run on its own (as opposed to running the entire suite). + # The second line in the assert_queries block was causing visit_Arel_Attributes_Attribute + # in Arel::Visitors::ToSql to trigger a SHOW TABLES query. Running that line here causes + # the SHOW TABLES result to be cached so we don't have to do it again in the block. + # + # This is obviously a rubbish fix but it's the best I can come up with for now... + posts.where(:id => nil).any? + assert_queries(3) do assert posts.any? # Uses COUNT() assert ! posts.where(:id => nil).any? -- cgit v1.2.3 From 3103296a61709e808aa89c3d37cf22bcdbc5a675 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sun, 2 Jan 2011 20:33:18 +0000 Subject: Let AssociationCollection#find use #scoped to do its finding. Note that I am removing test_polymorphic_has_many_going_through_join_model_with_disabled_include, since this specifies different behaviour for an association than for a regular scope. It seems reasonable to expect scopes and association proxies to behave in roughly the same way rather than having subtle differences. --- activerecord/test/cases/associations/join_model_test.rb | 7 ------- activerecord/test/cases/readonly_test.rb | 15 ++++++++------- activerecord/test/cases/relations_test.rb | 4 ++++ activerecord/test/models/comment.rb | 5 +++++ activerecord/test/models/post.rb | 2 +- activerecord/test/models/project.rb | 4 ++++ 6 files changed, 22 insertions(+), 15 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb index 263c90097f..7e9c190f42 100644 --- a/activerecord/test/cases/associations/join_model_test.rb +++ b/activerecord/test/cases/associations/join_model_test.rb @@ -85,13 +85,6 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase end end - def test_polymorphic_has_many_going_through_join_model_with_disabled_include - assert_equal tags(:general), tag = posts(:welcome).tags.add_joins_and_select.first - assert_queries 1 do - tag.tagging - end - end - def test_polymorphic_has_many_going_through_join_model_with_custom_select_and_joins assert_equal tags(:general), tag = posts(:welcome).tags.add_joins_and_select.first tag.author_id diff --git a/activerecord/test/cases/readonly_test.rb b/activerecord/test/cases/readonly_test.rb index a1eb96ef09..8d694900ff 100644 --- a/activerecord/test/cases/readonly_test.rb +++ b/activerecord/test/cases/readonly_test.rb @@ -6,11 +6,6 @@ require 'models/project' require 'models/reader' require 'models/person' -# Dummy class methods to test implicit association scoping. -def Comment.foo() find :first end -def Project.foo() find :first end - - class ReadOnlyTest < ActiveRecord::TestCase fixtures :posts, :comments, :developers, :projects, :developers_projects, :people, :readers @@ -114,7 +109,13 @@ class ReadOnlyTest < ActiveRecord::TestCase end def test_association_collection_method_missing_scoping_not_readonly - assert !Developer.find(1).projects.foo.readonly? - assert !Post.find(1).comments.foo.readonly? + developer = Developer.find(1) + project = Post.find(1) + + assert !developer.projects.all_as_method.first.readonly? + assert !developer.projects.all_as_scope.first.readonly? + + assert !project.comments.all_as_method.first.readonly? + assert !project.comments.all_as_scope.first.readonly? end end diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index cd774ce343..4de180880c 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -806,4 +806,8 @@ class RelationTest < ActiveRecord::TestCase assert_equal [rails_author], [rails_author] & relation assert_equal [rails_author], relation & [rails_author] end + + def test_removing_limit_with_options + assert_not_equal 1, Post.limit(1).all(:limit => nil).count + end end diff --git a/activerecord/test/models/comment.rb b/activerecord/test/models/comment.rb index 88061b2145..a9aa0afced 100644 --- a/activerecord/test/models/comment.rb +++ b/activerecord/test/models/comment.rb @@ -15,6 +15,11 @@ class Comment < ActiveRecord::Base def self.search_by_type(q) self.find(:all, :conditions => ["#{QUOTED_TYPE} = ?", q]) end + + def self.all_as_method + all + end + scope :all_as_scope, {} end class SpecialComment < Comment diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index b51f7ff48f..1c95d30d6b 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -51,7 +51,7 @@ class Post < ActiveRecord::Base has_many :taggings, :as => :taggable has_many :tags, :through => :taggings do def add_joins_and_select - find :all, :select => 'tags.*, authors.id as author_id', :include => false, + find :all, :select => 'tags.*, authors.id as author_id', :joins => 'left outer join posts on taggings.taggable_id = posts.id left outer join authors on posts.author_id = authors.id' end end diff --git a/activerecord/test/models/project.rb b/activerecord/test/models/project.rb index 416032cb75..8a53a8f803 100644 --- a/activerecord/test/models/project.rb +++ b/activerecord/test/models/project.rb @@ -28,6 +28,10 @@ class Project < ActiveRecord::Base @developers_log = [] end + def self.all_as_method + all + end + scope :all_as_scope, {} end class SpecialProject < Project -- cgit v1.2.3 From 1313d386dacb580858e5951418a637f4e17cf5c1 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Mon, 3 Jan 2011 10:04:40 +0000 Subject: Make Relation#create_with always merge rather than overwrite, not just when merging two relations. If you wish to overwrite, you can do relation.create_with(nil), or for a specific attribute, relation.create_with(:attr => nil). --- activerecord/test/cases/relation_scoping_test.rb | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/relation_scoping_test.rb b/activerecord/test/cases/relation_scoping_test.rb index 7c6899d438..bff0151f1a 100644 --- a/activerecord/test/cases/relation_scoping_test.rb +++ b/activerecord/test/cases/relation_scoping_test.rb @@ -491,5 +491,15 @@ class DefaultScopingTest < ActiveRecord::TestCase PoorDeveloperCalledJamis.create_with(:name => 'Aaron')).new assert_equal 20, aaron.salary assert_equal 'Aaron', aaron.name + + aaron = PoorDeveloperCalledJamis.create_with(:name => 'foo', :salary => 20). + create_with(:name => 'Aaron').new + assert_equal 20, aaron.salary + assert_equal 'Aaron', aaron.name + end + + def test_create_with_reset + jamis = PoorDeveloperCalledJamis.create_with(:name => 'Aaron').create_with(nil).new + assert_equal 'Jamis', jamis.name end end -- cgit v1.2.3 From a9bed985cfd7d1ae93f475542bb878aa939e1c1e Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Mon, 3 Jan 2011 13:38:40 +0000 Subject: When preloading a belongs_to, the target should still be set (to nil) if there is no foreign key present. And the loaded flag should be set on the association proxy. This then allows us to remove the foreign_key_present? check from BelongsToAssociation#find_target. Also added a test for the same thing on polymorphic associations. --- activerecord/test/cases/associations/eager_test.rb | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index 2a9351507a..e11f1009dc 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -212,6 +212,15 @@ class EagerAssociationTest < ActiveRecord::TestCase end end + def test_finding_with_includes_on_null_belongs_to_polymorphic_association + sponsor = sponsors(:moustache_club_sponsor_for_groucho) + sponsor.update_attributes!(:sponsorable => nil) + sponsor = assert_queries(1) { Sponsor.find(sponsor.id, :include => :sponsorable) } + assert_no_queries do + assert_equal nil, sponsor.sponsorable + end + end + def test_loading_from_an_association posts = authors(:david).posts.find(:all, :include => :comments, :order => "posts.id") assert_equal 2, posts.first.comments.size -- cgit v1.2.3 From 0619dc2319cf839977ea9670a52d9280a1af3595 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Mon, 3 Jan 2011 19:54:38 +0000 Subject: Implement deprecated version of AssociationReflection#primary_key_name, which has been renamed to #foreign_key. Also bumping the deprecation_horizon in Active Support to 3.1. --- activerecord/test/cases/reflection_test.rb | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index 081e3cc861..d75bc3982e 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -248,6 +248,18 @@ class ReflectionTest < ActiveRecord::TestCase assert !AssociationReflection.new(:has_and_belongs_to_many, :clients, { :autosave => true, :validate => false }, Firm).validate? end + def test_foreign_key + assert_equal "author_id", Author.reflect_on_association(:posts).foreign_key.to_s + assert_equal "category_id", Post.reflect_on_association(:categorizations).foreign_key.to_s + end + + def test_primary_key_name + assert_deprecated do + assert_equal "author_id", Author.reflect_on_association(:posts).primary_key_name.to_s + assert_equal "category_id", Post.reflect_on_association(:categorizations).primary_key_name.to_s + end + end + private def assert_reflection(klass, association, options) assert reflection = klass.reflect_on_association(association) -- cgit v1.2.3 From 2120da7f733ba33183a42e71256db9652c5f5fcc Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Mon, 3 Jan 2011 22:47:07 +0000 Subject: ActiveRecord::Relation#primary_key should return a string, just like ActiveRecord::Base.primary_key does. --- activerecord/test/cases/relations_test.rb | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 4de180880c..5018b16b67 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -810,4 +810,8 @@ class RelationTest < ActiveRecord::TestCase def test_removing_limit_with_options assert_not_equal 1, Post.limit(1).all(:limit => nil).count end + + def test_primary_key + assert_equal "id", Post.scoped.primary_key + end end -- cgit v1.2.3 From 40afcade0dc1450e765a91fc15a6ac6d442c9826 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Mon, 3 Jan 2011 23:48:53 +0000 Subject: Remove undocumented feature from has_one where you could pass false as the second parameter to build_assoc or create_assoc, and the existing associated object would be untouched (the foreign key would not be nullified, and it would not be deleted). If you want behaviour similar to this you can do the following things: * Use :dependent => :nullify (or don't specify :dependent) if you want to prevent the existing associated object from being deleted * Use has_many if you actually want multiple associated objects * Explicitly set the foreign key if, for some reason, you really need to have multiple objects associated with the same has_one. E.g. previous = obj.assoc obj.create_assoc previous.update_attributes(:obj_id => obj.id) --- .../associations/has_one_associations_test.rb | 29 ---------------------- .../associations/inverse_associations_test.rb | 14 +++++------ 2 files changed, 7 insertions(+), 36 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb index 64449df8f5..fa36b527a2 100644 --- a/activerecord/test/cases/associations/has_one_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_associations_test.rb @@ -116,35 +116,6 @@ class HasOneAssociationsTest < ActiveRecord::TestCase assert_equal company.account, account end - def test_assignment_without_replacement - apple = Firm.create("name" => "Apple") - citibank = Account.create("credit_limit" => 10) - apple.account = citibank - assert_equal apple.id, citibank.firm_id - - hsbc = apple.build_account({ :credit_limit => 20}, false) - assert_equal apple.id, hsbc.firm_id - hsbc.save - assert_equal apple.id, citibank.firm_id - - nykredit = apple.create_account({ :credit_limit => 30}, false) - assert_equal apple.id, nykredit.firm_id - assert_equal apple.id, citibank.firm_id - assert_equal apple.id, hsbc.firm_id - end - - def test_assignment_without_replacement_on_create - apple = Firm.create("name" => "Apple") - citibank = Account.create("credit_limit" => 10) - apple.account = citibank - assert_equal apple.id, citibank.firm_id - - hsbc = apple.create_account({:credit_limit => 10}, false) - assert_equal apple.id, hsbc.firm_id - hsbc.save - assert_equal apple.id, citibank.firm_id - end - def test_dependence num_accounts = Account.count diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb index 0491b2d1fa..a0f94a22e3 100644 --- a/activerecord/test/cases/associations/inverse_associations_test.rb +++ b/activerecord/test/cases/associations/inverse_associations_test.rb @@ -146,9 +146,9 @@ class InverseHasOneTests < ActiveRecord::TestCase assert_equal m.name, f.man.name, "Name of man should be the same after changes to newly-created-child-owned instance" end - def test_parent_instance_should_be_shared_with_newly_built_child_when_we_dont_replace_existing + def test_parent_instance_should_be_shared_with_newly_built_child m = Man.find(:first) - f = m.build_face({:description => 'haunted'}, false) + f = m.build_face(:description => 'haunted') assert_not_nil f.man assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance" m.name = 'Bongo' @@ -157,9 +157,9 @@ class InverseHasOneTests < ActiveRecord::TestCase assert_equal m.name, f.man.name, "Name of man should be the same after changes to just-built-child-owned instance" end - def test_parent_instance_should_be_shared_with_newly_created_child_when_we_dont_replace_existing + def test_parent_instance_should_be_shared_with_newly_created_child m = Man.find(:first) - f = m.create_face({:description => 'haunted'}, false) + f = m.create_face(:description => 'haunted') assert_not_nil f.man assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance" m.name = 'Bongo' @@ -168,9 +168,9 @@ class InverseHasOneTests < ActiveRecord::TestCase assert_equal m.name, f.man.name, "Name of man should be the same after changes to newly-created-child-owned instance" end - def test_parent_instance_should_be_shared_with_newly_created_child_via_bang_method_when_we_dont_replace_existing + def test_parent_instance_should_be_shared_with_newly_created_child_via_bang_method m = Man.find(:first) - f = m.face.create!({:description => 'haunted'}, false) + f = m.face.create!(:description => 'haunted') assert_not_nil f.man assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance" m.name = 'Bongo' @@ -203,7 +203,7 @@ class InverseHasOneTests < ActiveRecord::TestCase assert_equal m.name, f.man.name, "Name of man should be the same after changes to replaced-child-owned instance" end - def test_parent_instance_should_be_shared_with_replaced_via_method_child_when_we_dont_replace_existing + def test_parent_instance_should_be_shared_with_replaced_via_method_child m = Man.find(:first) f = Face.new(:description => 'haunted') m.face.replace(f, false) -- cgit v1.2.3 From 3f4143eedb3ec1c8e55bfc1ea0083fbb35749659 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 4 Jan 2011 15:16:56 -0800 Subject: fixing merge errors --- .../associations/belongs_to_associations_test.rb | 11 ---- .../associations/inverse_associations_test.rb | 67 ---------------------- 2 files changed, 78 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index 38ee4ad4e0..aaa5421eea 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -162,17 +162,6 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase assert_equal 0, Topic.find(debate.id).send(:read_attribute, "replies_count"), "First reply deleted" end - def test_belongs_to_with_primary_key_counter - debate = Topic.create("title" => "debate") - assert_equal 0, debate.send(:read_attribute, "replies_count"), "No replies yet" - - trash = debate.replies_with_primary_key.create("title" => "blah!", "content" => "world around!") - assert_equal 1, Topic.find(debate.id).send(:read_attribute, "replies_count"), "First reply created" - - trash.destroy - assert_equal 0, Topic.find(debate.id).send(:read_attribute, "replies_count"), "First reply deleted" - end - def test_belongs_to_counter_with_assigning_nil p = Post.find(1) c = Comment.find(1) diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb index a0f94a22e3..4cca78da9d 100644 --- a/activerecord/test/cases/associations/inverse_associations_test.rb +++ b/activerecord/test/cases/associations/inverse_associations_test.rb @@ -113,39 +113,6 @@ class InverseHasOneTests < ActiveRecord::TestCase assert_equal m.name, f.man.name, "Name of man should be the same after changes to child-owned instance" end - def test_parent_instance_should_be_shared_with_newly_built_child - m = men(:gordon) - f = m.build_face(:description => 'haunted') - assert_not_nil f.man - assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance" - m.name = 'Bongo' - assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance" - f.man.name = 'Mungo' - assert_equal m.name, f.man.name, "Name of man should be the same after changes to just-built-child-owned instance" - end - - def test_parent_instance_should_be_shared_with_newly_created_child - m = men(:gordon) - f = m.create_face(:description => 'haunted') - assert_not_nil f.man - assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance" - m.name = 'Bongo' - assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance" - f.man.name = 'Mungo' - assert_equal m.name, f.man.name, "Name of man should be the same after changes to newly-created-child-owned instance" - end - - def test_parent_instance_should_be_shared_with_newly_created_child_via_bang_method - m = Man.find(:first) - f = m.face.create!(:description => 'haunted') - assert_not_nil f.man - assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance" - m.name = 'Bongo' - assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance" - f.man.name = 'Mungo' - assert_equal m.name, f.man.name, "Name of man should be the same after changes to newly-created-child-owned instance" - end - def test_parent_instance_should_be_shared_with_newly_built_child m = Man.find(:first) f = m.build_face(:description => 'haunted') @@ -191,18 +158,6 @@ class InverseHasOneTests < ActiveRecord::TestCase assert_equal m.name, f.man.name, "Name of man should be the same after changes to replaced-child-owned instance" end - def test_parent_instance_should_be_shared_with_replaced_via_method_child - m = Man.find(:first) - f = Face.new(:description => 'haunted') - m.face.replace(f) - assert_not_nil f.man - assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance" - m.name = 'Bongo' - assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance" - f.man.name = 'Mungo' - assert_equal m.name, f.man.name, "Name of man should be the same after changes to replaced-child-owned instance" - end - def test_parent_instance_should_be_shared_with_replaced_via_method_child m = Man.find(:first) f = Face.new(:description => 'haunted') @@ -257,17 +212,6 @@ class InverseHasManyTests < ActiveRecord::TestCase end end - def test_parent_instance_should_be_shared_with_newly_built_child - m = men(:gordon) - i = m.interests.build(:topic => 'Industrial Revolution Re-enactment') - assert_not_nil i.man - assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance" - m.name = 'Bongo' - assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance" - i.man.name = 'Mungo' - assert_equal m.name, i.man.name, "Name of man should be the same after changes to just-built-child-owned instance" - end - def test_parent_instance_should_be_shared_with_newly_block_style_built_child m = Man.find(:first) i = m.interests.build {|ii| ii.topic = 'Industrial Revolution Re-enactment'} @@ -280,17 +224,6 @@ class InverseHasManyTests < ActiveRecord::TestCase assert_equal m.name, i.man.name, "Name of man should be the same after changes to just-built-child-owned instance" end - def test_parent_instance_should_be_shared_with_newly_created_child - m = men(:gordon) - i = m.interests.create(:topic => 'Industrial Revolution Re-enactment') - assert_not_nil i.man - assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance" - m.name = 'Bongo' - assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance" - i.man.name = 'Mungo' - assert_equal m.name, i.man.name, "Name of man should be the same after changes to newly-created-child-owned instance" - end - def test_parent_instance_should_be_shared_with_newly_created_via_bang_method_child m = Man.find(:first) i = m.interests.create!(:topic => 'Industrial Revolution Re-enactment') -- cgit v1.2.3 From 6d747108286790bb7f5fa9ffbfcbdf4a557a2785 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 5 Jan 2011 14:01:47 -0800 Subject: make sure that Psych can roundtrip an AR object --- activerecord/test/cases/yaml_serialization_test.rb | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/yaml_serialization_test.rb b/activerecord/test/cases/yaml_serialization_test.rb index 0fc9918744..7503b06126 100644 --- a/activerecord/test/cases/yaml_serialization_test.rb +++ b/activerecord/test/cases/yaml_serialization_test.rb @@ -17,4 +17,17 @@ class YamlSerializationTest < ActiveRecord::TestCase t = YAML.load YAML.dump topic assert_equal topic, t end + + begin + require 'psych' + + def test_psych_roundtrip + topic = Topic.first + assert topic + t = Psych.load Psych.dump topic + assert_equal topic, t + end + + rescue LoadError + end end -- cgit v1.2.3 From 97bc74c74611d3d71d58776ed907ebd0cdb98a15 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 5 Jan 2011 14:03:13 -0800 Subject: make sure new objects can round trip --- activerecord/test/cases/yaml_serialization_test.rb | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/yaml_serialization_test.rb b/activerecord/test/cases/yaml_serialization_test.rb index 7503b06126..abcf61ffc0 100644 --- a/activerecord/test/cases/yaml_serialization_test.rb +++ b/activerecord/test/cases/yaml_serialization_test.rb @@ -28,6 +28,12 @@ class YamlSerializationTest < ActiveRecord::TestCase assert_equal topic, t end + def test_psych_roundtrip_new_object + topic = Topic.new + assert topic + t = Psych.load Psych.dump topic + assert_equal topic.attributes, t.attributes + end rescue LoadError end end -- cgit v1.2.3 From eba8411652cb39529839083cf903f6ce76a69f4a Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 5 Jan 2011 14:59:19 -0800 Subject: adding an `encode_with` method for Psych dump/load methods --- activerecord/test/cases/yaml_serialization_test.rb | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/yaml_serialization_test.rb b/activerecord/test/cases/yaml_serialization_test.rb index abcf61ffc0..0b54c309d1 100644 --- a/activerecord/test/cases/yaml_serialization_test.rb +++ b/activerecord/test/cases/yaml_serialization_test.rb @@ -18,6 +18,13 @@ class YamlSerializationTest < ActiveRecord::TestCase assert_equal topic, t end + def test_encode_with_coder + topic = Topic.first + coder = {} + topic.encode_with coder + assert_equal({'attributes' => topic.attributes}, coder) + end + begin require 'psych' -- cgit v1.2.3 From 839f3bf6822ed3698df1e606c4215d650312f33e Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 7 Jan 2011 11:28:11 -0800 Subject: just use a hash for doing association caching --- activerecord/test/cases/associations/belongs_to_associations_test.rb | 4 ++-- activerecord/test/cases/inheritance_test.rb | 2 +- activerecord/test/cases/modules_test.rb | 1 - 3 files changed, 3 insertions(+), 4 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index aaa5421eea..1cb29a0fa1 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -78,14 +78,14 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase Firm.create("name" => "Apple") Client.create("name" => "Citibank", :firm_name => "Apple") citibank_result = Client.find(:first, :conditions => {:name => "Citibank"}, :include => :firm_with_primary_key) - assert_not_nil citibank_result.instance_variable_get("@firm_with_primary_key") + assert citibank_result.association_cache.key?(:firm_with_primary_key) end def test_eager_loading_with_primary_key_as_symbol Firm.create("name" => "Apple") Client.create("name" => "Citibank", :firm_name => "Apple") citibank_result = Client.find(:first, :conditions => {:name => "Citibank"}, :include => :firm_with_primary_key_symbols) - assert_not_nil citibank_result.instance_variable_get("@firm_with_primary_key_symbols") + assert citibank_result.association_cache.key?(:firm_with_primary_key_symbols) end def test_creating_the_belonging_object diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb index 9fac9373eb..680d4ca5dd 100644 --- a/activerecord/test/cases/inheritance_test.rb +++ b/activerecord/test/cases/inheritance_test.rb @@ -203,7 +203,7 @@ class InheritanceTest < ActiveRecord::TestCase def test_eager_load_belongs_to_something_inherited account = Account.find(1, :include => :firm) - assert_not_nil account.instance_variable_get("@firm"), "nil proves eager load failed" + assert account.association_cache.key?(:firm), "nil proves eager load failed" end def test_eager_load_belongs_to_primary_key_quoting diff --git a/activerecord/test/cases/modules_test.rb b/activerecord/test/cases/modules_test.rb index 14870cb0e2..a2041af16a 100644 --- a/activerecord/test/cases/modules_test.rb +++ b/activerecord/test/cases/modules_test.rb @@ -49,7 +49,6 @@ class ModulesTest < ActiveRecord::TestCase def test_find_account_and_include_company account = MyApplication::Billing::Account.find(1, :include => :firm) - assert_kind_of MyApplication::Business::Firm, account.instance_variable_get('@firm') assert_kind_of MyApplication::Business::Firm, account.firm end -- cgit v1.2.3 From 2efd780dcb91b9df5eb05ae8b4837602a33c16fc Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 7 Jan 2011 14:30:20 -0800 Subject: send() will raise an ArgumentError, so we should leverage ruby --- activerecord/test/models/customer.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/models/customer.rb b/activerecord/test/models/customer.rb index e258ccdb6c..777f6b5ba0 100644 --- a/activerecord/test/models/customer.rb +++ b/activerecord/test/models/customer.rb @@ -70,4 +70,4 @@ class Fullname def to_s "#{first} #{last.upcase}" end -end \ No newline at end of file +end -- cgit v1.2.3 From 441118458d57011ee1b1f1dcfea558de462c6da9 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Thu, 6 Jan 2011 17:01:24 +0000 Subject: Use encode_with for marshalling --- activerecord/test/cases/base_test.rb | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 594f3b80c6..a58d5dec81 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -1503,4 +1503,11 @@ class BasicsTest < ActiveRecord::TestCase ensure Object.class_eval{ remove_const :UnloadablePost } if defined?(UnloadablePost) end + + def test_marshal_round_trip + expected = posts(:welcome) + actual = Marshal.load(Marshal.dump(expected)) + + assert_equal expected.attributes, actual.attributes + end end -- cgit v1.2.3 From 770e6893b9f2aaaebe3de10576931dc7194451bc Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Thu, 6 Jan 2011 18:04:32 +0000 Subject: Construct an actual ActiveRecord::Relation object for the association scope, rather than a hash which is passed to apply_finder_options. This allows more flexibility in how the scope is created, for example because scope.where(a, b) and scope.where(a).where(b) mean different things. --- activerecord/test/cases/associations/has_one_associations_test.rb | 8 -------- activerecord/test/cases/reflection_test.rb | 4 ++-- activerecord/test/cases/relation_scoping_test.rb | 3 ++- activerecord/test/models/company.rb | 1 - 4 files changed, 4 insertions(+), 12 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb index fa36b527a2..8203534a37 100644 --- a/activerecord/test/cases/associations/has_one_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_associations_test.rb @@ -227,14 +227,6 @@ class HasOneAssociationsTest < ActiveRecord::TestCase firm.destroy end - def test_finding_with_interpolated_condition - firm = Firm.find(:first) - superior = firm.clients.create(:name => 'SuperiorCo') - superior.rating = 10 - superior.save - assert_equal 10, firm.clients_with_interpolated_conditions.first.rating - end - def test_assignment_before_child_saved firm = Firm.find(1) firm.account = a = Account.new("credit_limit" => 1000) diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index d75bc3982e..eb580928ba 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -181,8 +181,8 @@ class ReflectionTest < ActiveRecord::TestCase def test_reflection_of_all_associations # FIXME these assertions bust a lot - assert_equal 37, Firm.reflect_on_all_associations.size - assert_equal 27, Firm.reflect_on_all_associations(:has_many).size + assert_equal 36, Firm.reflect_on_all_associations.size + assert_equal 26, Firm.reflect_on_all_associations(:has_many).size assert_equal 10, Firm.reflect_on_all_associations(:has_one).size assert_equal 0, Firm.reflect_on_all_associations(:belongs_to).size end diff --git a/activerecord/test/cases/relation_scoping_test.rb b/activerecord/test/cases/relation_scoping_test.rb index bff0151f1a..1bdf3136d4 100644 --- a/activerecord/test/cases/relation_scoping_test.rb +++ b/activerecord/test/cases/relation_scoping_test.rb @@ -259,7 +259,8 @@ class HasManyScopingTest< ActiveRecord::TestCase end def test_should_default_scope_on_associations_is_overriden_by_association_conditions - assert_equal [], people(:michael).fixed_bad_references + reference = references(:michael_unicyclist).becomes(BadReference) + assert_equal [reference], people(:michael).fixed_bad_references end def test_should_maintain_default_scope_on_eager_loaded_associations diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb index d08e593db1..f6e7a5ccf7 100644 --- a/activerecord/test/models/company.rb +++ b/activerecord/test/models/company.rb @@ -49,7 +49,6 @@ class Firm < Company has_many :exclusively_dependent_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :delete_all has_many :limited_clients, :class_name => "Client", :limit => 1 has_many :clients_like_ms, :conditions => "name = 'Microsoft'", :class_name => "Client", :order => "id" - has_many :clients_with_interpolated_conditions, :class_name => "Client", :conditions => 'rating > #{rating}' has_many :clients_like_ms_with_hash_conditions, :conditions => { :name => 'Microsoft' }, :class_name => "Client", :order => "id" has_many :clients_using_sql, :class_name => "Client", :finder_sql => 'SELECT * FROM companies WHERE client_of = #{id}' has_many :clients_using_multiline_sql, :class_name => "Client", :finder_sql => ' -- cgit v1.2.3 From 5b28e5254267c581ce6934408aaf458616e44e3f Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Thu, 6 Jan 2011 19:54:23 +0000 Subject: Don't not remove double negatives --- activerecord/test/cases/associations/inverse_associations_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb index 4cca78da9d..e9a57a00a0 100644 --- a/activerecord/test/cases/associations/inverse_associations_test.rb +++ b/activerecord/test/cases/associations/inverse_associations_test.rb @@ -161,7 +161,7 @@ class InverseHasOneTests < ActiveRecord::TestCase def test_parent_instance_should_be_shared_with_replaced_via_method_child m = Man.find(:first) f = Face.new(:description => 'haunted') - m.face.replace(f, false) + m.face.replace(f) assert_not_nil f.man assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance" m.name = 'Bongo' -- cgit v1.2.3 From 63ed6ca9989fbfcd2b323b98e4110c7504b8d3db Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Fri, 7 Jan 2011 16:24:06 -0800 Subject: Add test for e0e3adf --- activerecord/test/cases/attribute_methods_test.rb | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb index e3cbae4a84..a29e4349d6 100644 --- a/activerecord/test/cases/attribute_methods_test.rb +++ b/activerecord/test/cases/attribute_methods_test.rb @@ -247,6 +247,12 @@ class AttributeMethodsTest < ActiveRecord::TestCase # puts "" end + def test_read_overridden_attribute + topic = Topic.new(:title => 'a') + def topic.title() 'b' end + assert_equal 'a', topic[:title] + end + def test_query_attribute_string [nil, "", " "].each do |value| assert_equal false, Topic.new(:author_name => value).author_name? -- cgit v1.2.3 From 06165856196ac17b87163d146abea46019b17032 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 10 Jan 2011 11:36:23 -0800 Subject: use SQLite3::VERSION rather than the deprecated class --- activerecord/test/cases/query_cache_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/query_cache_test.rb b/activerecord/test/cases/query_cache_test.rb index 33916c4e46..53aefc7b58 100644 --- a/activerecord/test/cases/query_cache_test.rb +++ b/activerecord/test/cases/query_cache_test.rb @@ -63,7 +63,7 @@ class QueryCacheTest < ActiveRecord::TestCase # Oracle adapter returns count() as Fixnum or Float if current_adapter?(:OracleAdapter) assert_kind_of Numeric, Task.connection.select_value("SELECT count(*) AS count_all FROM tasks") - elsif current_adapter?(:SQLite3Adapter) && SQLite3::Version::VERSION > '1.2.5' || current_adapter?(:Mysql2Adapter) || current_adapter?(:MysqlAdapter) + elsif current_adapter?(:SQLite3Adapter) && SQLite3::VERSION > '1.2.5' || current_adapter?(:Mysql2Adapter) || current_adapter?(:MysqlAdapter) # Future versions of the sqlite3 adapter will return numeric assert_instance_of Fixnum, Task.connection.select_value("SELECT count(*) AS count_all FROM tasks") -- cgit v1.2.3 From f4f4964ce0a05cac38bbff3b308ac558228bad29 Mon Sep 17 00:00:00 2001 From: Raimonds Simanovskis Date: Mon, 10 Jan 2011 18:55:32 +0200 Subject: Always return decimal average of integer fields In previous version if database adapter (e.g. SQLite and Oracle) returned non-String calculated values then type_cast_using_column converted decimal average value of intefer field to integer value. Now operation parameter is always checked to decide which conversion of calculated value should be done. --- activerecord/test/cases/calculations_test.rb | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index 5cb8485b4b..644c9cb528 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -23,6 +23,11 @@ class CalculationsTest < ActiveRecord::TestCase assert_equal 53.0, value end + def test_should_return_decimal_average_of_integer_field + value = Account.average(:id) + assert_equal 3.5, value + end + def test_should_return_nil_as_average assert_nil NumericData.average(:bank_balance) end -- cgit v1.2.3 From 7d4d7457301faa85aa32b5ae29e13976e828954f Mon Sep 17 00:00:00 2001 From: Ernie Miller Date: Thu, 6 Jan 2011 20:06:29 -0500 Subject: Fix polymorphic belongs_to associationproxy raising errors when loading target. --- .../test/cases/associations/belongs_to_associations_test.rb | 9 +++++++++ activerecord/test/models/sponsor.rb | 2 ++ 2 files changed, 11 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index 1cb29a0fa1..4c4891dcaf 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -146,6 +146,15 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase assert_not_nil Company.find(3).firm_with_condition, "Microsoft should have a firm" end + def test_with_polymorphic_and_condition + sponsor = Sponsor.create + member = Member.create :name => "Bert" + sponsor.sponsorable = member + + assert_equal member, sponsor.sponsorable + assert_nil sponsor.sponsorable_with_conditions + end + def test_with_select assert_equal Company.find(2).firm_with_select.attributes.size, 1 assert_equal Company.find(2, :include => :firm_with_select ).firm_with_select.attributes.size, 1 diff --git a/activerecord/test/models/sponsor.rb b/activerecord/test/models/sponsor.rb index 7e5a1dc38b..aa4a3638fd 100644 --- a/activerecord/test/models/sponsor.rb +++ b/activerecord/test/models/sponsor.rb @@ -2,4 +2,6 @@ class Sponsor < ActiveRecord::Base belongs_to :sponsor_club, :class_name => "Club", :foreign_key => "club_id" belongs_to :sponsorable, :polymorphic => true belongs_to :thing, :polymorphic => true, :foreign_type => :sponsorable_type, :foreign_key => :sponsorable_id + belongs_to :sponsorable_with_conditions, :polymorphic => true, + :foreign_type => 'sponsorable_type', :foreign_key => 'sponsorable_id', :conditions => {:name => 'Ernie'} end -- cgit v1.2.3 From c6e10b0f600a56e962ff7d1614c50fca20630379 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Fri, 7 Jan 2011 19:12:37 +0000 Subject: has_one should always remove the old record (properly), even if not saving the new record, so we don't get the database into a pickle --- .../associations/has_one_associations_test.rb | 35 +++++++++++++++------- activerecord/test/fixtures/ships.yml | 1 + activerecord/test/models/pirate.rb | 4 +++ 3 files changed, 30 insertions(+), 10 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb index 8203534a37..f004d46c98 100644 --- a/activerecord/test/cases/associations/has_one_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_associations_test.rb @@ -2,9 +2,11 @@ require "cases/helper" require 'models/developer' require 'models/project' require 'models/company' +require 'models/ship' +require 'models/pirate' class HasOneAssociationsTest < ActiveRecord::TestCase - fixtures :accounts, :companies, :developers, :projects, :developers_projects + fixtures :accounts, :companies, :developers, :projects, :developers_projects, :ships, :pirates def setup Account.destroyed_account_ids.clear @@ -164,15 +166,6 @@ class HasOneAssociationsTest < ActiveRecord::TestCase assert_equal account, firm.account end - def test_build_association_twice_without_saving_affects_nothing - count_of_account = Account.count - firm = Firm.find(:first) - firm.build_account("credit_limit" => 1000) - firm.build_account("credit_limit" => 2000) - - assert_equal count_of_account, Account.count - end - def test_create_association firm = Firm.create(:name => "GlobalMegaCorp") account = firm.create_account(:credit_limit => 1000) @@ -293,4 +286,26 @@ class HasOneAssociationsTest < ActiveRecord::TestCase new_account = companies(:first_firm).build_account(:firm_name => 'Account') assert_equal new_account.firm_name, "Account" end + + def test_creation_failure_without_dependent_option + pirate = pirates(:blackbeard) + orig_ship = pirate.ship.target + + assert_equal ships(:black_pearl), orig_ship + new_ship = pirate.create_ship + assert_not_equal ships(:black_pearl), new_ship + assert_equal new_ship, pirate.ship + assert new_ship.new_record? + assert_nil orig_ship.pirate_id + assert !orig_ship.changed? # check it was saved + end + + def test_creation_failure_with_dependent_option + pirate = pirates(:blackbeard).becomes(DestructivePirate) + orig_ship = pirate.dependent_ship.target + + new_ship = pirate.create_dependent_ship + assert new_ship.new_record? + assert orig_ship.destroyed? + end end diff --git a/activerecord/test/fixtures/ships.yml b/activerecord/test/fixtures/ships.yml index 137055aad1..df914262b3 100644 --- a/activerecord/test/fixtures/ships.yml +++ b/activerecord/test/fixtures/ships.yml @@ -1,5 +1,6 @@ black_pearl: name: "Black Pearl" + pirate: blackbeard interceptor: id: 2 name: "Interceptor" diff --git a/activerecord/test/models/pirate.rb b/activerecord/test/models/pirate.rb index f2c45053e7..b0490f754e 100644 --- a/activerecord/test/models/pirate.rb +++ b/activerecord/test/models/pirate.rb @@ -78,3 +78,7 @@ class Pirate < ActiveRecord::Base ship_log << "#{callback}_#{record.class.name.downcase}_#{record.id || ''}" end end + +class DestructivePirate < Pirate + has_one :dependent_ship, :class_name => 'Ship', :foreign_key => :pirate_id, :dependent => :destroy +end -- cgit v1.2.3 From 80df74bf515124c9db85d4a670989ae5cc28c3ec Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sat, 8 Jan 2011 18:33:33 +0000 Subject: Enable the sqlite3 in-memory test connection to work --- activerecord/test/cases/helper.rb | 16 +++++++++++----- activerecord/test/cases/locking_test.rb | 4 ++-- activerecord/test/cases/pooled_connections_test.rb | 2 +- activerecord/test/cases/unconnected_test.rb | 1 + .../native_sqlite3/in_memory_connection.rb | 19 ++++++++++--------- 5 files changed, 25 insertions(+), 17 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index f9bbc5299b..51104d9cf5 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -26,6 +26,11 @@ def current_adapter?(*types) end end +def in_memory_db? + current_adapter?(:SQLiteAdapter) && + ActiveRecord::Base.connection_pool.spec.config[:database] == ":memory:" +end + def with_env_tz(new_tz = 'US/Eastern') old_tz, ENV['TZ'] = ENV['TZ'], new_tz yield @@ -100,11 +105,11 @@ class ActiveSupport::TestCase end end -# silence verbose schema loading -original_stdout = $stdout -$stdout = StringIO.new +def load_schema + # silence verbose schema loading + original_stdout = $stdout + $stdout = StringIO.new -begin adapter_name = ActiveRecord::Base.connection.adapter_name.downcase adapter_specific_schema_file = SCHEMA_ROOT + "/#{adapter_name}_specific_schema.rb" @@ -117,6 +122,8 @@ ensure $stdout = original_stdout end +load_schema + class << Time unless method_defined? :now_before_time_travel alias_method :now_before_time_travel, :now @@ -133,4 +140,3 @@ class << Time @now = nil end end - diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb index f9678cb0c5..71667defa7 100644 --- a/activerecord/test/cases/locking_test.rb +++ b/activerecord/test/cases/locking_test.rb @@ -252,13 +252,13 @@ end # TODO: The Sybase, and OpenBase adapters currently have no support for pessimistic locking -unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter) +unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter) || in_memory_db? class PessimisticLockingTest < ActiveRecord::TestCase self.use_transactional_fixtures = false fixtures :people, :readers def setup - Person.connection_pool.clear_reloadable_connections! + Person.connection_pool.clear_reloadable_connections # Avoid introspection queries during tests. Person.columns; Reader.columns end diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb index de5fa140ba..6269437b14 100644 --- a/activerecord/test/cases/pooled_connections_test.rb +++ b/activerecord/test/cases/pooled_connections_test.rb @@ -137,4 +137,4 @@ class PooledConnectionsTest < ActiveRecord::TestCase def add_record(name) ActiveRecord::Base.connection_pool.with_connection { Project.create! :name => name } end -end unless %w(FrontBase).include? ActiveRecord::Base.connection.adapter_name +end unless current_adapter?(:FrontBase) || in_memory_db? diff --git a/activerecord/test/cases/unconnected_test.rb b/activerecord/test/cases/unconnected_test.rb index 23ad10f3f9..e82ca3f93d 100644 --- a/activerecord/test/cases/unconnected_test.rb +++ b/activerecord/test/cases/unconnected_test.rb @@ -14,6 +14,7 @@ class TestUnconnectedAdapter < ActiveRecord::TestCase def teardown @underlying = nil ActiveRecord::Base.establish_connection(@specification) + load_schema if in_memory_db? end def test_connection_no_longer_established diff --git a/activerecord/test/connections/native_sqlite3/in_memory_connection.rb b/activerecord/test/connections/native_sqlite3/in_memory_connection.rb index 6aba9719bb..14e10900d1 100644 --- a/activerecord/test/connections/native_sqlite3/in_memory_connection.rb +++ b/activerecord/test/connections/native_sqlite3/in_memory_connection.rb @@ -1,4 +1,8 @@ -print "Using native SQLite3\n" +# This file connects to an in-memory SQLite3 database, which is a very fast way to run the tests. +# The downside is that disconnect from the database results in the database effectively being +# wiped. For this reason, pooled_connections_test.rb is disabled when using an in-memory database. + +print "Using native SQLite3 (in memory)\n" require_dependency 'models/course' require 'logger' ActiveRecord::Base.logger = Logger.new("debug.log") @@ -6,13 +10,10 @@ ActiveRecord::Base.logger = Logger.new("debug.log") class SqliteError < StandardError end -def make_connection(clazz, db_definitions_file) - clazz.establish_connection(:adapter => 'sqlite3', :database => ':memory:') - File.read(SCHEMA_ROOT + "/#{db_definitions_file}").split(';').each do |command| - clazz.connection.execute(command) unless command.strip.empty? - end +def make_connection(clazz) + ActiveRecord::Base.configurations = { clazz.name => { :adapter => 'sqlite3', :database => ':memory:' } } + clazz.establish_connection(clazz.name) end -make_connection(ActiveRecord::Base, 'sqlite.sql') -make_connection(Course, 'sqlite2.sql') -load(SCHEMA_ROOT + "/schema.rb") +make_connection(ActiveRecord::Base) +make_connection(Course) -- cgit v1.2.3 From c47c54140246f4e5b49376ae9c408c85968ed6c3 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sat, 8 Jan 2011 18:36:30 +0000 Subject: Have a separate test connection directory for sqlite3 in-memory so that the tests can be run without having to specifically rename the connection file (which then causes git to pick up the changes) --- .../native_sqlite3/in_memory_connection.rb | 19 ------------------- .../test/connections/native_sqlite3_mem/connection.rb | 19 +++++++++++++++++++ 2 files changed, 19 insertions(+), 19 deletions(-) delete mode 100644 activerecord/test/connections/native_sqlite3/in_memory_connection.rb create mode 100644 activerecord/test/connections/native_sqlite3_mem/connection.rb (limited to 'activerecord/test') diff --git a/activerecord/test/connections/native_sqlite3/in_memory_connection.rb b/activerecord/test/connections/native_sqlite3/in_memory_connection.rb deleted file mode 100644 index 14e10900d1..0000000000 --- a/activerecord/test/connections/native_sqlite3/in_memory_connection.rb +++ /dev/null @@ -1,19 +0,0 @@ -# This file connects to an in-memory SQLite3 database, which is a very fast way to run the tests. -# The downside is that disconnect from the database results in the database effectively being -# wiped. For this reason, pooled_connections_test.rb is disabled when using an in-memory database. - -print "Using native SQLite3 (in memory)\n" -require_dependency 'models/course' -require 'logger' -ActiveRecord::Base.logger = Logger.new("debug.log") - -class SqliteError < StandardError -end - -def make_connection(clazz) - ActiveRecord::Base.configurations = { clazz.name => { :adapter => 'sqlite3', :database => ':memory:' } } - clazz.establish_connection(clazz.name) -end - -make_connection(ActiveRecord::Base) -make_connection(Course) diff --git a/activerecord/test/connections/native_sqlite3_mem/connection.rb b/activerecord/test/connections/native_sqlite3_mem/connection.rb new file mode 100644 index 0000000000..14e10900d1 --- /dev/null +++ b/activerecord/test/connections/native_sqlite3_mem/connection.rb @@ -0,0 +1,19 @@ +# This file connects to an in-memory SQLite3 database, which is a very fast way to run the tests. +# The downside is that disconnect from the database results in the database effectively being +# wiped. For this reason, pooled_connections_test.rb is disabled when using an in-memory database. + +print "Using native SQLite3 (in memory)\n" +require_dependency 'models/course' +require 'logger' +ActiveRecord::Base.logger = Logger.new("debug.log") + +class SqliteError < StandardError +end + +def make_connection(clazz) + ActiveRecord::Base.configurations = { clazz.name => { :adapter => 'sqlite3', :database => ':memory:' } } + clazz.establish_connection(clazz.name) +end + +make_connection(ActiveRecord::Base) +make_connection(Course) -- cgit v1.2.3 From 1bc71ed9607ba88c21c14b670a4308c8549f3941 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sat, 8 Jan 2011 19:39:40 +0000 Subject: When assigning a has_one, if the existing record fails to be removed from the association, raise an error --- .../test/cases/associations/has_one_associations_test.rb | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb index f004d46c98..46459df7c5 100644 --- a/activerecord/test/cases/associations/has_one_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_associations_test.rb @@ -308,4 +308,16 @@ class HasOneAssociationsTest < ActiveRecord::TestCase assert new_ship.new_record? assert orig_ship.destroyed? end + + def test_replacement_failure_due_to_existing_record_should_raise_error + pirate = pirates(:blackbeard) + pirate.ship.name = nil + + assert !pirate.ship.valid? + assert_raise(ActiveRecord::RecordNotSaved) do + pirate.ship = ships(:interceptor) + end + assert_equal ships(:black_pearl), pirate.ship + assert_equal pirate.id, pirate.ship.pirate_id + end end -- cgit v1.2.3 From 7f7b480098fa780dd76b4c1243230d74be67b3ca Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sat, 8 Jan 2011 19:59:30 +0000 Subject: When assigning a has_one, if the new record fails to save, raise an error --- .../associations/has_one_associations_test.rb | 28 +++++++++++----------- .../test/cases/autosave_association_test.rb | 4 ++-- 2 files changed, 16 insertions(+), 16 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb index 46459df7c5..b9719fa983 100644 --- a/activerecord/test/cases/associations/has_one_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_associations_test.rb @@ -93,18 +93,18 @@ class HasOneAssociationsTest < ActiveRecord::TestCase def test_nullification_on_association_change firm = companies(:rails_core) old_account_id = firm.account.id - firm.account = Account.new + firm.account = Account.new(:credit_limit => 5) # account is dependent with nullify, therefore its firm_id should be nil assert_nil Account.find(old_account_id).firm_id end def test_association_change_calls_delete - companies(:first_firm).deletable_account = Account.new + companies(:first_firm).deletable_account = Account.new(:credit_limit => 5) assert_equal [], Account.destroyed_account_ids[companies(:first_firm).id] end def test_association_change_calls_destroy - companies(:first_firm).account = Account.new + companies(:first_firm).account = Account.new(:credit_limit => 5) assert_equal [companies(:first_firm).id], Account.destroyed_account_ids[companies(:first_firm).id] end @@ -182,17 +182,6 @@ class HasOneAssociationsTest < ActiveRecord::TestCase assert_equal account, firm.account end - def test_failing_build_association - firm = Firm.new("name" => "GlobalMegaCorp") - firm.save - - firm.account = account = Account.new - assert_equal account, firm.account - assert !account.save - assert_equal account, firm.account - assert_equal ["can't be empty"], account.errors["credit_limit"] - end - def test_create firm = Firm.new("name" => "GlobalMegaCorp") firm.save @@ -320,4 +309,15 @@ class HasOneAssociationsTest < ActiveRecord::TestCase assert_equal ships(:black_pearl), pirate.ship assert_equal pirate.id, pirate.ship.pirate_id end + + def test_replacement_failure_due_to_new_record_should_raise_error + pirate = pirates(:blackbeard) + new_ship = Ship.new + + assert_raise(ActiveRecord::RecordNotSaved) do + pirate.ship = new_ship + end + assert_equal new_ship, pirate.ship + assert_equal pirate.id, new_ship.pirate_id + end end diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index 71fd3fd836..2e43a20a73 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -90,7 +90,7 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas firm = Firm.find(:first) assert firm.valid? - firm.account = Account.new + firm.build_account assert !firm.account.valid? assert !firm.valid? @@ -102,7 +102,7 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas firm = Firm.find(:first) assert firm.valid? - firm.unvalidated_account = Account.new + firm.build_unvalidated_account assert !firm.unvalidated_account.valid? assert firm.valid? -- cgit v1.2.3 From 4e19ec566c9132b85fdf0ff13a328238a6aca591 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sun, 9 Jan 2011 15:52:41 +0000 Subject: In a number of places in the tests, we only need to turn off transactional fixtures when the DB does not support savepoints. This speeds the test run up by about 8-9% on my computer, when running rake test_sqlite3_mem :) --- .../test/cases/associations/join_model_test.rb | 3 +- .../test/cases/autosave_association_test.rb | 20 ++++---- activerecord/test/cases/helper.rb | 4 ++ activerecord/test/cases/locking_test.rb | 54 ++++++++++++---------- activerecord/test/cases/migration_test.rb | 3 +- activerecord/test/cases/multiple_db_test.rb | 2 +- activerecord/test/cases/nested_attributes_test.rb | 4 +- .../test/cases/session_store/session_test.rb | 2 +- activerecord/test/cases/unconnected_test.rb | 2 +- 9 files changed, 51 insertions(+), 43 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb index 7e9c190f42..512a6d3ef8 100644 --- a/activerecord/test/cases/associations/join_model_test.rb +++ b/activerecord/test/cases/associations/join_model_test.rb @@ -13,7 +13,8 @@ require 'models/book' require 'models/citation' class AssociationsJoinModelTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_fixtures = false unless supports_savepoints? + fixtures :posts, :authors, :categories, :categorizations, :comments, :tags, :taggings, :author_favorites, :vertices, :items, :books, # Reload edges table from fixtures as otherwise repeated test was failing :edges diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index 2e43a20a73..11c0c5b0ef 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -572,7 +572,7 @@ class TestDefaultAutosaveAssociationOnNewRecord < ActiveRecord::TestCase end class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_fixtures = false unless supports_savepoints? def setup @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") @@ -797,7 +797,7 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase end class TestAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_fixtures = false unless supports_savepoints? def setup @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") @@ -917,7 +917,7 @@ class TestAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase end class TestAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_fixtures = false unless supports_savepoints? def setup @ship = Ship.create(:name => 'Nights Dirty Lightning') @@ -1164,7 +1164,7 @@ module AutosaveAssociationOnACollectionAssociationTests end class TestAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_fixtures = false unless supports_savepoints? def setup @association_name = :birds @@ -1178,7 +1178,7 @@ class TestAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCase end class TestAutosaveAssociationOnAHasAndBelongsToManyAssociation < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_fixtures = false unless supports_savepoints? def setup @association_name = :parrots @@ -1193,7 +1193,7 @@ class TestAutosaveAssociationOnAHasAndBelongsToManyAssociation < ActiveRecord::T end class TestAutosaveAssociationValidationsOnAHasManyAssociation < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_fixtures = false unless supports_savepoints? def setup @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") @@ -1209,7 +1209,7 @@ class TestAutosaveAssociationValidationsOnAHasManyAssociation < ActiveRecord::Te end class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_fixtures = false unless supports_savepoints? def setup @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") @@ -1230,7 +1230,7 @@ class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::Tes end class TestAutosaveAssociationValidationsOnABelongsToAssociation < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_fixtures = false unless supports_savepoints? def setup @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") @@ -1250,7 +1250,7 @@ class TestAutosaveAssociationValidationsOnABelongsToAssociation < ActiveRecord:: end class TestAutosaveAssociationValidationsOnAHABTMAssociation < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_fixtures = false unless supports_savepoints? def setup @pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?") @@ -1272,7 +1272,7 @@ class TestAutosaveAssociationValidationsOnAHABTMAssociation < ActiveRecord::Test end class TestAutosaveAssociationValidationMethodsGeneration < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_fixtures = false unless supports_savepoints? def setup @pirate = Pirate.new diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 51104d9cf5..2cc993b6ed 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -31,6 +31,10 @@ def in_memory_db? ActiveRecord::Base.connection_pool.spec.config[:database] == ":memory:" end +def supports_savepoints? + ActiveRecord::Base.connection.supports_savepoints? +end + def with_env_tz(new_tz = 'US/Eastern') old_tz, ENV['TZ'] = ENV['TZ'], new_tz yield diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb index 71667defa7..c5a204b335 100644 --- a/activerecord/test/cases/locking_test.rb +++ b/activerecord/test/cases/locking_test.rb @@ -19,11 +19,6 @@ end class OptimisticLockingTest < ActiveRecord::TestCase fixtures :people, :legacy_things, :references - # need to disable transactional fixtures, because otherwise the sqlite3 - # adapter (at least) chokes when we try and change the schema in the middle - # of a test (see test_increment_counter_*). - self.use_transactional_fixtures = false - def test_lock_existing p1 = Person.find(1) p2 = Person.find(1) @@ -152,6 +147,33 @@ class OptimisticLockingTest < ActiveRecord::TestCase assert_equal "unchangeable name", p.first_name end + def test_quote_table_name + ref = references(:michael_magician) + ref.favourite = !ref.favourite + assert ref.save + end + + # Useful for partial updates, don't only update the lock_version if there + # is nothing else being updated. + def test_update_without_attributes_does_not_only_update_lock_version + assert_nothing_raised do + p1 = Person.create!(:first_name => 'anika') + lock_version = p1.lock_version + p1.save + p1.reload + assert_equal lock_version, p1.lock_version + end + end +end + +class OptimisticLockingWithSchemaChangeTest < ActiveRecord::TestCase + fixtures :people, :legacy_things, :references + + # need to disable transactional fixtures, because otherwise the sqlite3 + # adapter (at least) chokes when we try and change the schema in the middle + # of a test (see test_increment_counter_*). + self.use_transactional_fixtures = false + { :lock_version => Person, :custom_lock_version => LegacyThing }.each do |name, model| define_method("test_increment_counter_updates_#{name}") do counter_test model, 1 do |id| @@ -198,24 +220,6 @@ class OptimisticLockingTest < ActiveRecord::TestCase assert_raises(ActiveRecord::RecordNotFound) { LegacyThing.find(t.id) } end - def test_quote_table_name - ref = references(:michael_magician) - ref.favourite = !ref.favourite - assert ref.save - end - - # Useful for partial updates, don't only update the lock_version if there - # is nothing else being updated. - def test_update_without_attributes_does_not_only_update_lock_version - assert_nothing_raised do - p1 = Person.create!(:first_name => 'anika') - lock_version = p1.lock_version - p1.save - p1.reload - assert_equal lock_version, p1.lock_version - end - end - private def add_counter_column_to(model, col='test_count') @@ -254,11 +258,11 @@ end unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter) || in_memory_db? class PessimisticLockingTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_fixtures = false unless supports_savepoints? fixtures :people, :readers def setup - Person.connection_pool.clear_reloadable_connections + Person.connection_pool.clear_reloadable_connections! # Avoid introspection queries during tests. Person.columns; Reader.columns end diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index 1a65045ded..a5a9965c3a 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -14,7 +14,7 @@ if ActiveRecord::Base.connection.supports_migrations? class Reminder < ActiveRecord::Base; end class ActiveRecord::Migration - class < "My baby takes tha mornin' train!") @@ -899,7 +899,7 @@ class TestHasOneAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveRe end class TestHasManyAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_fixtures = false unless supports_savepoints? def setup @ship = Ship.create!(:name => "The good ship Dollypop") diff --git a/activerecord/test/cases/session_store/session_test.rb b/activerecord/test/cases/session_store/session_test.rb index 6f1c170a0c..f906bda8c3 100644 --- a/activerecord/test/cases/session_store/session_test.rb +++ b/activerecord/test/cases/session_store/session_test.rb @@ -5,7 +5,7 @@ require 'active_record/session_store' module ActiveRecord class SessionStore class SessionTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_fixtures = false unless supports_savepoints? && ActiveRecord::Base.connection.supports_ddl_transactions? def setup super diff --git a/activerecord/test/cases/unconnected_test.rb b/activerecord/test/cases/unconnected_test.rb index e82ca3f93d..f85fb4e5da 100644 --- a/activerecord/test/cases/unconnected_test.rb +++ b/activerecord/test/cases/unconnected_test.rb @@ -4,7 +4,7 @@ class TestRecord < ActiveRecord::Base end class TestUnconnectedAdapter < ActiveRecord::TestCase - self.use_transactional_fixtures = false + self.use_transactional_fixtures = false unless supports_savepoints? def setup @underlying = ActiveRecord::Base.connection -- cgit v1.2.3 From 1d6e2184283d15d20ed3102ca462d905e5efa73d Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sun, 9 Jan 2011 16:06:14 +0000 Subject: When assigning a has_one, if anything fails, the assignment should be rolled back entirely --- activerecord/test/cases/associations/has_one_associations_test.rb | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb index b9719fa983..925b76b901 100644 --- a/activerecord/test/cases/associations/has_one_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_associations_test.rb @@ -6,6 +6,7 @@ require 'models/ship' require 'models/pirate' class HasOneAssociationsTest < ActiveRecord::TestCase + self.use_transactional_fixtures = false unless supports_savepoints? fixtures :accounts, :companies, :developers, :projects, :developers_projects, :ships, :pirates def setup @@ -317,7 +318,9 @@ class HasOneAssociationsTest < ActiveRecord::TestCase assert_raise(ActiveRecord::RecordNotSaved) do pirate.ship = new_ship end - assert_equal new_ship, pirate.ship - assert_equal pirate.id, new_ship.pirate_id + assert_equal ships(:black_pearl), pirate.ship + assert_equal pirate.id, pirate.ship.pirate_id + assert_equal pirate.id, ships(:black_pearl).reload.pirate_id + assert_nil new_ship.pirate_id end end -- cgit v1.2.3 From 6055bbedaa4b7b4bb2377ac87147196eebb2edc1 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sun, 9 Jan 2011 16:34:23 +0000 Subject: Raise ActiveRecord::RecordNotSaved if an AssociationCollection fails to be replaced --- .../test/cases/associations/has_many_associations_test.rb | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 2b7ad3642a..1ce91d7211 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -975,6 +975,19 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert !firm.clients.include?(:first_client) end + def test_replace_failure + firm = companies(:first_firm) + account = Account.new + orig_accounts = firm.accounts.to_a + + assert !account.valid? + assert !orig_accounts.empty? + assert_raise ActiveRecord::RecordNotSaved do + firm.accounts = [account] + end + assert_equal orig_accounts, firm.accounts + end + def test_get_ids assert_equal [companies(:first_client).id, companies(:second_client).id], companies(:first_firm).client_ids end -- cgit v1.2.3 From 3b797c8c8681c8f4619bce39d3f042244fe002d9 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sun, 9 Jan 2011 17:13:05 +0000 Subject: DRY up the code which instantiates the association proxy --- .../test/cases/validations/uniqueness_validation_test.rb | 13 ------------- activerecord/test/models/reply.rb | 7 +++++++ activerecord/test/models/topic.rb | 4 ++++ 3 files changed, 11 insertions(+), 13 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/validations/uniqueness_validation_test.rb b/activerecord/test/cases/validations/uniqueness_validation_test.rb index 679d67553b..b4f3dd034c 100644 --- a/activerecord/test/cases/validations/uniqueness_validation_test.rb +++ b/activerecord/test/cases/validations/uniqueness_validation_test.rb @@ -6,19 +6,6 @@ require 'models/warehouse_thing' require 'models/guid' require 'models/event' -# The following methods in Topic are used in test_conditional_validation_* -class Topic - has_many :unique_replies, :dependent => :destroy, :foreign_key => "parent_id" - has_many :silly_unique_replies, :dependent => :destroy, :foreign_key => "parent_id" -end - -class UniqueReply < Reply - validates_uniqueness_of :content, :scope => 'parent_id' -end - -class SillyUniqueReply < UniqueReply -end - class Wizard < ActiveRecord::Base self.abstract_class = true diff --git a/activerecord/test/models/reply.rb b/activerecord/test/models/reply.rb index 110d540120..6adfe0ae3c 100644 --- a/activerecord/test/models/reply.rb +++ b/activerecord/test/models/reply.rb @@ -10,6 +10,13 @@ class Reply < Topic attr_accessible :title, :author_name, :author_email_address, :written_on, :content, :last_read, :parent_title end +class UniqueReply < Reply + validates_uniqueness_of :content, :scope => 'parent_id' +end + +class SillyUniqueReply < UniqueReply +end + class WrongReply < Reply validate :errors_on_empty_content validate :title_is_wrong_create, :on => :create diff --git a/activerecord/test/models/topic.rb b/activerecord/test/models/topic.rb index 6496f36f7e..6440dbe8ab 100644 --- a/activerecord/test/models/topic.rb +++ b/activerecord/test/models/topic.rb @@ -45,6 +45,10 @@ class Topic < ActiveRecord::Base has_many :replies, :dependent => :destroy, :foreign_key => "parent_id" has_many :replies_with_primary_key, :class_name => "Reply", :dependent => :destroy, :primary_key => "title", :foreign_key => "parent_title" + + has_many :unique_replies, :dependent => :destroy, :foreign_key => "parent_id" + has_many :silly_unique_replies, :dependent => :destroy, :foreign_key => "parent_id" + serialize :content before_create :default_written_on -- cgit v1.2.3 From 681ab53ba15f9fc95c8a91e50bb0138aa66967b2 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sun, 9 Jan 2011 18:37:01 +0000 Subject: Get rid of set_association_target and association_loaded? as the parts of the code that need that can now just use association_proxy(:name).loaded?/target= --- .../test/cases/associations/has_one_through_associations_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb index 0afbef5c87..91d3025468 100644 --- a/activerecord/test/cases/associations/has_one_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb @@ -197,7 +197,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase MemberDetail.find(:all, :include => :member_type) end @new_detail = @member_details[0] - assert @new_detail.loaded_member_type? + assert @new_detail.send(:association_proxy, :member_type).loaded? assert_not_nil assert_no_queries { @new_detail.member_type } end -- cgit v1.2.3 From 552df9b933e05a3c1d2508c316f1f2bd240accc5 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sun, 9 Jan 2011 19:09:51 +0000 Subject: Support for create_association! for has_one associations --- .../cases/associations/has_one_associations_test.rb | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb index 925b76b901..d9b6694dd8 100644 --- a/activerecord/test/cases/associations/has_one_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_associations_test.rb @@ -173,6 +173,24 @@ class HasOneAssociationsTest < ActiveRecord::TestCase assert_equal account, firm.reload.account end + def test_create_association_with_bang + firm = Firm.create(:name => "GlobalMegaCorp") + account = firm.create_account!(:credit_limit => 1000) + assert_equal account, firm.reload.account + end + + def test_create_association_with_bang_failing + firm = Firm.create(:name => "GlobalMegaCorp") + assert_raise ActiveRecord::RecordInvalid do + firm.create_account! + end + account = firm.account + assert_not_nil account + account.credit_limit = 5 + account.save + assert_equal account, firm.reload.account + end + def test_build firm = Firm.new("name" => "GlobalMegaCorp") firm.save -- cgit v1.2.3 From fcd8925f236b391d562dc504bcd901f501140c11 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 11 Jan 2011 15:39:26 -0800 Subject: use underlying _read_attribute method rather than causing NoMethodErrors --- activerecord/test/cases/associations/join_model_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb index 512a6d3ef8..c50fcd3f33 100644 --- a/activerecord/test/cases/associations/join_model_test.rb +++ b/activerecord/test/cases/associations/join_model_test.rb @@ -523,7 +523,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase def test_has_many_through_collection_size_uses_counter_cache_if_it_exists author = authors(:david) - author.stubs(:read_attribute).with('comments_count').returns(100) + author.stubs(:_read_attribute).with('comments_count').returns(100) assert_equal 100, author.comments.size assert !author.comments.loaded? end -- cgit v1.2.3 From f8700038afdaea80cad34a4fca005e1ef068b53e Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 11 Jan 2011 17:57:02 -0800 Subject: adding a test for no method error --- .../cases/associations/association_proxy_test.rb | 52 ++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 activerecord/test/cases/associations/association_proxy_test.rb (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/association_proxy_test.rb b/activerecord/test/cases/associations/association_proxy_test.rb new file mode 100644 index 0000000000..55d8da4c4e --- /dev/null +++ b/activerecord/test/cases/associations/association_proxy_test.rb @@ -0,0 +1,52 @@ +require "cases/helper" + +module ActiveRecord + module Associations + class AsssociationProxyTest < ActiveRecord::TestCase + class FakeOwner + attr_accessor :new_record + alias :new_record? :new_record + + def initialize + @new_record = false + end + end + + class FakeReflection < Struct.new(:options, :klass) + def initialize options = {}, klass = nil + super + end + + def check_validity! + true + end + end + + class FakeTarget + end + + class FakeTargetProxy < AssociationProxy + def association_scope + true + end + + def find_target + FakeTarget.new + end + end + + def test_method_missing_error + reflection = FakeReflection.new({}, Object.new) + owner = FakeOwner.new + proxy = FakeTargetProxy.new(owner, reflection) + + exception = assert_raises(NoMethodError) do + proxy.omg + end + + assert_match('omg', exception.message) + assert_match(FakeTarget.name, exception.message) + end + end + end +end -- cgit v1.2.3 From 3165dca28c1db741994c3176e7b158a9f684e816 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 12 Jan 2011 18:01:02 -0800 Subject: include_in_memory? should check against @target list in case of new records. [#6257 state:resolved] --- .../test/cases/associations/has_many_through_associations_test.rb | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index e98d178ff5..7235631b5a 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -32,6 +32,13 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase Reader.create :person_id => 0, :post_id => 0 end + def test_include? + person = Person.new + post = Post.new + person.posts << post + assert person.posts.include?(post) + end + def test_associate_existing assert_queries(2) { posts(:thinking); people(:david) } -- cgit v1.2.3 From 3755ae04a1933762fce99d148734dc3de2a184c1 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Fri, 14 Jan 2011 17:11:15 -0200 Subject: Add missing require --- activerecord/test/cases/associations/eager_load_nested_include_test.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/eager_load_nested_include_test.rb b/activerecord/test/cases/associations/eager_load_nested_include_test.rb index c7671a8c22..8957586189 100644 --- a/activerecord/test/cases/associations/eager_load_nested_include_test.rb +++ b/activerecord/test/cases/associations/eager_load_nested_include_test.rb @@ -4,6 +4,7 @@ require 'models/author' require 'models/comment' require 'models/category' require 'models/categorization' +require 'models/tagging' require 'active_support/core_ext/array/random_access' module Remembered -- cgit v1.2.3 From 1e9685f15921d1acec65d07a27640aa1c674a29b Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 14 Jan 2011 11:16:31 -0800 Subject: preheat the table cache in arel --- activerecord/test/cases/batches_test.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/batches_test.rb b/activerecord/test/cases/batches_test.rb index dcc49e12ca..6f65fb96d1 100644 --- a/activerecord/test/cases/batches_test.rb +++ b/activerecord/test/cases/batches_test.rb @@ -7,6 +7,7 @@ class EachTest < ActiveRecord::TestCase def setup @posts = Post.order("id asc") @total = Post.count + Post.count('id') # preheat arel's table cache end def test_each_should_excecute_one_query_per_batch -- cgit v1.2.3 From f30a3106f3cba97ace9a5ec36b8c18e3f38ee043 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 14 Jan 2011 13:45:30 -0800 Subject: transactional fixtures must be set to false for this test --- activerecord/test/cases/multiple_db_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/multiple_db_test.rb b/activerecord/test/cases/multiple_db_test.rb index 36e2c62fbb..bd51388e05 100644 --- a/activerecord/test/cases/multiple_db_test.rb +++ b/activerecord/test/cases/multiple_db_test.rb @@ -6,7 +6,7 @@ require 'models/bird' require_dependency 'models/course' class MultipleDbTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? + self.use_transactional_fixtures = false def setup @courses = create_fixtures("courses") { Course.retrieve_connection } -- cgit v1.2.3 From 2947197421dd6b00a3c6694b768322d095cda69b Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 14 Jan 2011 14:07:16 -0800 Subject: use rake to create test databases for us --- activerecord/test/connections/native_sqlite3/connection.rb | 9 --------- 1 file changed, 9 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/connections/native_sqlite3/connection.rb b/activerecord/test/connections/native_sqlite3/connection.rb index c517c2375e..c2aff5551f 100644 --- a/activerecord/test/connections/native_sqlite3/connection.rb +++ b/activerecord/test/connections/native_sqlite3/connection.rb @@ -3,21 +3,12 @@ require_dependency 'models/course' require 'logger' ActiveRecord::Base.logger = Logger.new("debug.log") -class SqliteError < StandardError -end - BASE_DIR = FIXTURES_ROOT sqlite_test_db = "#{BASE_DIR}/fixture_database.sqlite3" sqlite_test_db2 = "#{BASE_DIR}/fixture_database_2.sqlite3" def make_connection(clazz, db_file) ActiveRecord::Base.configurations = { clazz.name => { :adapter => 'sqlite3', :database => db_file, :timeout => 5000 } } - unless File.exist?(db_file) - puts "SQLite3 database not found at #{db_file}. Rebuilding it." - sqlite_command = %Q{sqlite3 "#{db_file}" "create table a (a integer); drop table a;"} - puts "Executing '#{sqlite_command}'" - raise SqliteError.new("Seems that there is no sqlite3 executable available") unless system(sqlite_command) - end clazz.establish_connection(clazz.name) end -- cgit v1.2.3 From 52c47556b7cf55549f97f3cfd5f69b2563198eac Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sun, 16 Jan 2011 18:25:50 +0000 Subject: Add create_association! for belongs_to --- .../cases/associations/belongs_to_associations_test.rb | 17 +++++++++++++++++ activerecord/test/models/company.rb | 1 + activerecord/test/schema/schema.rb | 1 + 3 files changed, 19 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index 4c4891dcaf..ef6c482f67 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -120,6 +120,23 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase assert_equal apple.name, client.firm_name end + def test_create! + client = Client.create!(:name => "Jimmy") + account = client.create_account!(:credit_limit => 10) + assert_equal account, client.account + assert account.persisted? + client.save + client.reload + assert_equal account, client.account + end + + def test_failing_create! + client = Client.create!(:name => "Jimmy") + assert_raise(ActiveRecord::RecordInvalid) { client.create_account! } + assert_not_nil client.account + assert client.account.new_record? + end + def test_natural_assignment_to_nil client = Client.find(3) client.firm = nil diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb index f6e7a5ccf7..e8a126fb28 100644 --- a/activerecord/test/models/company.rb +++ b/activerecord/test/models/company.rb @@ -124,6 +124,7 @@ class Client < Company belongs_to :firm_with_primary_key_symbols, :class_name => "Firm", :primary_key => :name, :foreign_key => :firm_name belongs_to :readonly_firm, :class_name => "Firm", :foreign_key => "firm_id", :readonly => true has_many :accounts, :through => :firm + belongs_to :account # Record destruction so we can test whether firm.clients.clear has # is calling client.destroy, deleting from the database, or setting diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 7f366b2c91..5f9bb7ee41 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -154,6 +154,7 @@ ActiveRecord::Schema.define do t.string :name t.integer :client_of t.integer :rating, :default => 1 + t.integer :account_id end add_index :companies, [:firm_id, :type, :rating, :ruby_type], :name => "company_index" -- cgit v1.2.3 From bf24fe810c0591619ac01cc88d8a40423895d9d7 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sun, 16 Jan 2011 19:20:37 +0000 Subject: belongs_to records should be initialized within the association scope --- .../associations/belongs_to_associations_test.rb | 21 +++++++++++++++++++++ activerecord/test/models/company.rb | 1 + 2 files changed, 22 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index ef6c482f67..01073bca3d 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -608,4 +608,25 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase assert_equal groucho, sponsor.sponsorable assert_equal groucho, sponsor.thing end + + def test_build_with_conditions + client = companies(:second_client) + firm = client.build_bob_firm + + assert_equal "Bob", firm.name + end + + def test_create_with_conditions + client = companies(:second_client) + firm = client.create_bob_firm + + assert_equal "Bob", firm.name + end + + def test_create_bang_with_conditions + client = companies(:second_client) + firm = client.create_bob_firm! + + assert_equal "Bob", firm.name + end end diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb index e8a126fb28..3e219fbe4a 100644 --- a/activerecord/test/models/company.rb +++ b/activerecord/test/models/company.rb @@ -123,6 +123,7 @@ class Client < Company belongs_to :firm_with_primary_key, :class_name => "Firm", :primary_key => "name", :foreign_key => "firm_name" belongs_to :firm_with_primary_key_symbols, :class_name => "Firm", :primary_key => :name, :foreign_key => :firm_name belongs_to :readonly_firm, :class_name => "Firm", :foreign_key => "firm_id", :readonly => true + belongs_to :bob_firm, :class_name => "Firm", :foreign_key => "client_of", :conditions => { :name => "Bob" } has_many :accounts, :through => :firm belongs_to :account -- cgit v1.2.3 From d1521719c5ac61a0c0e59827fe8cb197f5fe56f5 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sun, 16 Jan 2011 21:28:47 +0000 Subject: Removed support for accessing attributes on a has_and_belongs_to_many join table. This has been documented as deprecated behaviour since April 2006. Please use has_many :through instead. A deprecation warning will be added to the 3-0-stable branch for the 3.0.4 release. --- .../has_and_belongs_to_many_associations_test.rb | 83 ---------------------- activerecord/test/cases/readonly_test.rb | 9 --- 2 files changed, 92 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index 705550216c..30730c7094 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -101,38 +101,6 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase assert_equal 't1', record[1] end - def test_should_record_timestamp_for_join_table - setup_data_for_habtm_case - - con = ActiveRecord::Base.connection - sql = 'select * from countries_treaties' - record = con.select_rows(sql).last - assert_not_nil record[2] - assert_not_nil record[3] - if current_adapter?(:Mysql2Adapter, :OracleAdapter) - assert_match %r{\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}}, record[2].to_s(:db) - assert_match %r{\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}}, record[3].to_s(:db) - else - assert_match %r{\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}}, record[2] - assert_match %r{\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}}, record[3] - end - end - - def test_should_record_timestamp_for_join_table_only_if_timestamp_should_be_recorded - begin - Treaty.record_timestamps = false - setup_data_for_habtm_case - - con = ActiveRecord::Base.connection - sql = 'select * from countries_treaties' - record = con.select_rows(sql).last - assert_nil record[2] - assert_nil record[3] - ensure - Treaty.record_timestamps = true - end - end - def test_has_and_belongs_to_many david = Developer.find(1) @@ -218,34 +186,6 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase assert_equal 2, aredridel.projects(true).size end - def test_adding_uses_default_values_on_join_table - ac = projects(:action_controller) - assert !developers(:jamis).projects.include?(ac) - developers(:jamis).projects << ac - - assert developers(:jamis, :reload).projects.include?(ac) - project = developers(:jamis).projects.detect { |p| p == ac } - assert_equal 1, project.access_level.to_i - end - - def test_habtm_attribute_access_and_respond_to - project = developers(:jamis).projects[0] - assert project.has_attribute?("name") - assert project.has_attribute?("joined_on") - assert project.has_attribute?("access_level") - assert project.respond_to?("name") - assert project.respond_to?("name=") - assert project.respond_to?("name?") - assert project.respond_to?("joined_on") - # given that the 'join attribute' won't be persisted, I don't - # think we should define the mutators - #assert project.respond_to?("joined_on=") - assert project.respond_to?("joined_on?") - assert project.respond_to?("access_level") - #assert project.respond_to?("access_level=") - assert project.respond_to?("access_level?") - end - def test_habtm_adding_before_save no_of_devels = Developer.count no_of_projects = Project.count @@ -430,10 +370,6 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase assert DeveloperWithBeforeDestroyRaise.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = 1").empty? end - def test_additional_columns_from_join_table - assert_date_from_db Date.new(2004, 10, 10), Developer.find(1).projects.first.joined_on.to_date - end - def test_destroying david = Developer.find(1) active_record = Project.find(1) @@ -675,25 +611,6 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase assert_respond_to categories(:technology).select_testing_posts.find(:first), :correctness_marker end - def test_updating_attributes_on_rich_associations - david = projects(:action_controller).developers.first - david.name = "DHH" - assert_raise(ActiveRecord::ReadOnlyRecord) { david.save! } - end - - def test_updating_attributes_on_rich_associations_with_limited_find_from_reflection - david = projects(:action_controller).selected_developers.first - david.name = "DHH" - assert_nothing_raised { david.save! } - end - - - def test_updating_attributes_on_rich_associations_with_limited_find - david = projects(:action_controller).developers.find(:all, :select => "developers.*").first - david.name = "DHH" - assert david.save! - end - def test_join_table_alias assert_equal 3, Developer.find(:all, :include => {:projects => :developers}, :conditions => 'developers_projects_join.joined_on IS NOT NULL').size end diff --git a/activerecord/test/cases/readonly_test.rb b/activerecord/test/cases/readonly_test.rb index 8d694900ff..e21109baae 100644 --- a/activerecord/test/cases/readonly_test.rb +++ b/activerecord/test/cases/readonly_test.rb @@ -44,15 +44,6 @@ class ReadOnlyTest < ActiveRecord::TestCase Developer.joins(', projects').readonly(false).each { |d| assert !d.readonly? } end - - def test_habtm_find_readonly - dev = Developer.find(1) - assert !dev.projects.empty? - assert dev.projects.all?(&:readonly?) - assert dev.projects.find(:all).all?(&:readonly?) - assert dev.projects.readonly(true).all?(&:readonly?) - end - def test_has_many_find_readonly post = Post.find(1) assert !post.comments.empty? -- cgit v1.2.3 From fdfabc99e80d5c48bdaf1c046c592ac81dc4c2c6 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 17 Jan 2011 14:22:17 -0800 Subject: fixing unused variable warnings --- activerecord/test/cases/adapters/mysql/reserved_word_test.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb index 90d8b0d923..b5c938b14a 100644 --- a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb +++ b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb @@ -105,9 +105,9 @@ class MysqlReservedWordTest < ActiveRecord::TestCase assert_nothing_raised { x.save } x.order = 'y' assert_nothing_raised { x.save } - assert_nothing_raised { y = Group.find_by_order('y') } - assert_nothing_raised { y = Group.find(1) } - x = Group.find(1) + assert_nothing_raised { Group.find_by_order('y') } + assert_nothing_raised { Group.find(1) } + Group.find(1) end # has_one association with reserved-word table name -- cgit v1.2.3 From e6881217ed8d7a20f70bb482a43512978fc4fc3b Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 18 Jan 2011 10:49:50 -0800 Subject: fixing bug where 1.8 hangs while running pg tests --- activerecord/test/cases/locking_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb index c5a204b335..2a72838d06 100644 --- a/activerecord/test/cases/locking_test.rb +++ b/activerecord/test/cases/locking_test.rb @@ -258,7 +258,7 @@ end unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter) || in_memory_db? class PessimisticLockingTest < ActiveRecord::TestCase - self.use_transactional_fixtures = false unless supports_savepoints? + self.use_transactional_fixtures = false fixtures :people, :readers def setup -- cgit v1.2.3 From 2884482c3494b909e8e64751cfb0b588748d8854 Mon Sep 17 00:00:00 2001 From: Alexey Nayden Date: Thu, 13 Jan 2011 00:22:38 +0300 Subject: test_first_and_array_index_zero_methods_return_the_same_value_when_nested_attributes_are_set_to_update_existing_record added --- activerecord/test/cases/nested_attributes_test.rb | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index e1f938be84..ef25bde87e 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -147,6 +147,15 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase pirate.ship_attributes = { :id => "" } assert_nothing_raised(ActiveRecord::RecordNotFound) { pirate.save! } end + + def test_first_and_array_index_zero_methods_return_the_same_value_when_nested_attributes_are_set_to_update_existing_record + Man.accepts_nested_attributes_for(:interests) + man = Man.create(:name => "John") + interest = Interest.create :topic => 'gardning', :man => man + man = Man.first + man.interests_attributes = [{:id => interest.id, :topic => 'gardening'}] + assert_equal man.interests.first.topic, man.interests[0].topic + end end class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase -- cgit v1.2.3 From fa779c5357fd9396644ffc46e8ec575444f2f029 Mon Sep 17 00:00:00 2001 From: Alexey Nayden Date: Thu, 13 Jan 2011 03:50:37 +0300 Subject: Fixing incorrectly writtent testcase --- activerecord/test/cases/nested_attributes_test.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index ef25bde87e..d1afe7376a 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -151,8 +151,8 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase def test_first_and_array_index_zero_methods_return_the_same_value_when_nested_attributes_are_set_to_update_existing_record Man.accepts_nested_attributes_for(:interests) man = Man.create(:name => "John") - interest = Interest.create :topic => 'gardning', :man => man - man = Man.first + interest = man.interests.create :topic => 'gardning' + man = Man.find man.id man.interests_attributes = [{:id => interest.id, :topic => 'gardening'}] assert_equal man.interests.first.topic, man.interests[0].topic end -- cgit v1.2.3 From 63c73dd0214188dc91442db538e141e30ec3b1b9 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sun, 23 Jan 2011 21:29:36 +0000 Subject: We shouldn't be using scoped.scoping { ... } to build associated records, as this can affect validations/callbacks/etc inside the record itself [#6252 state:resolved] --- .../cases/associations/has_many_associations_test.rb | 18 +++++++++++++++++- .../cases/associations/has_one_associations_test.rb | 15 +++++++++++++++ activerecord/test/models/bulb.rb | 11 +++++++++-- activerecord/test/models/pirate.rb | 2 ++ 4 files changed, 43 insertions(+), 3 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 1ce91d7211..2ca412d424 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -43,7 +43,7 @@ end class HasManyAssociationsTest < ActiveRecord::TestCase fixtures :accounts, :categories, :companies, :developers, :projects, :developers_projects, :topics, :authors, :comments, - :people, :posts, :readers, :taggings + :people, :posts, :readers, :taggings, :cars def setup Client.destroyed_client_ids.clear @@ -66,6 +66,22 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal 'exotic', bulb.name end + # When creating objects on the association, we must not do it within a scope (even though it + # would be convenient), because this would cause that scope to be applied to any callbacks etc. + def test_build_and_create_should_not_happen_within_scope + car = cars(:honda) + original_scoped_methods = Bulb.scoped_methods + + bulb = car.bulbs.build + assert_equal original_scoped_methods, bulb.scoped_methods_after_initialize + + bulb = car.bulbs.create + assert_equal original_scoped_methods, bulb.scoped_methods_after_initialize + + bulb = car.bulbs.create! + assert_equal original_scoped_methods, bulb.scoped_methods_after_initialize + end + def test_no_sql_should_be_fired_if_association_already_loaded Car.create(:name => 'honda') bulbs = Car.first.bulbs diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb index d9b6694dd8..dbf6dfe20d 100644 --- a/activerecord/test/cases/associations/has_one_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_associations_test.rb @@ -4,6 +4,7 @@ require 'models/project' require 'models/company' require 'models/ship' require 'models/pirate' +require 'models/bulb' class HasOneAssociationsTest < ActiveRecord::TestCase self.use_transactional_fixtures = false unless supports_savepoints? @@ -167,6 +168,20 @@ class HasOneAssociationsTest < ActiveRecord::TestCase assert_equal account, firm.account end + def test_build_and_create_should_not_happen_within_scope + pirate = pirates(:blackbeard) + original_scoped_methods = Bulb.scoped_methods.dup + + bulb = pirate.build_bulb + assert_equal original_scoped_methods, bulb.scoped_methods_after_initialize + + bulb = pirate.create_bulb + assert_equal original_scoped_methods, bulb.scoped_methods_after_initialize + + bulb = pirate.create_bulb! + assert_equal original_scoped_methods, bulb.scoped_methods_after_initialize + end + def test_create_association firm = Firm.create(:name => "GlobalMegaCorp") account = firm.create_account(:credit_limit => 1000) diff --git a/activerecord/test/models/bulb.rb b/activerecord/test/models/bulb.rb index 9eefc5803a..7178bb0d00 100644 --- a/activerecord/test/models/bulb.rb +++ b/activerecord/test/models/bulb.rb @@ -1,7 +1,14 @@ class Bulb < ActiveRecord::Base - + default_scope :conditions => {:name => 'defaulty' } - + belongs_to :car + attr_reader :scoped_methods_after_initialize + + after_initialize :record_scoped_methods_after_initialize + def record_scoped_methods_after_initialize + @scoped_methods_after_initialize = self.class.scoped_methods.dup + end + end diff --git a/activerecord/test/models/pirate.rb b/activerecord/test/models/pirate.rb index b0490f754e..0d3f62bb33 100644 --- a/activerecord/test/models/pirate.rb +++ b/activerecord/test/models/pirate.rb @@ -34,6 +34,8 @@ class Pirate < ActiveRecord::Base :after_remove => proc {|p,b| p.ship_log << "after_removing_proc_bird_#{b.id}"} has_many :birds_with_reject_all_blank, :class_name => "Bird" + has_one :bulb, :foreign_key => :car_id + accepts_nested_attributes_for :parrots, :birds, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? } accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? } accepts_nested_attributes_for :update_only_ship, :update_only => true -- cgit v1.2.3 From b7bcc7e1905062f330e0a84b93a1ecacfea2a4c0 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Mon, 24 Jan 2011 22:25:32 +0000 Subject: DRY up first/last and hence make last benefit from the bugfix in first --- activerecord/test/cases/associations/has_many_associations_test.rb | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 2ca412d424..3bec9c97f4 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -86,10 +86,16 @@ class HasManyAssociationsTest < ActiveRecord::TestCase Car.create(:name => 'honda') bulbs = Car.first.bulbs bulbs.inspect # to load all instances of bulbs + assert_no_queries do bulbs.first() bulbs.first({}) end + + assert_no_queries do + bulbs.last() + bulbs.last({}) + end end def test_create_resets_cached_counters -- cgit v1.2.3 From 88df88095c82cde53501abe2a44f6c1f66c272b4 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Mon, 24 Jan 2011 23:30:11 +0000 Subject: AssociationCollection#to_ary should definitely dup the target! Also changed #replace which was previously incorrect, but the test passed due to the fact that to_a was not duping. --- activerecord/test/cases/associations/has_many_associations_test.rb | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 3bec9c97f4..5904966ee5 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -1349,4 +1349,11 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal reply.id, first.id assert_equal true, first.approved? end + + def test_to_a_should_dup_target + ary = topics(:first).replies.to_a + target = topics(:first).replies.target + + assert_not_equal target.object_id, ary.object_id + end end -- cgit v1.2.3 From 2e24cf7cc2392c8fa252ef3b4831a4516ae852d6 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Mon, 24 Jan 2011 23:43:44 +0000 Subject: AssociationCollection#clear can basically just use #delete_all, except it should return self. --- .../test/cases/associations/has_many_associations_test.rb | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 5904966ee5..e36124a055 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -662,8 +662,10 @@ class HasManyAssociationsTest < ActiveRecord::TestCase def test_delete_all force_signal37_to_load_all_clients_of_firm companies(:first_firm).clients_of_firm.create("name" => "Another Client") - assert_equal 2, companies(:first_firm).clients_of_firm.size - companies(:first_firm).clients_of_firm.delete_all + clients = companies(:first_firm).clients_of_firm.to_a + assert_equal 2, clients.count + deleted = companies(:first_firm).clients_of_firm.delete_all + assert_equal clients.sort_by(&:id), deleted.sort_by(&:id) assert_equal 0, companies(:first_firm).clients_of_firm.size assert_equal 0, companies(:first_firm).clients_of_firm(true).size end @@ -683,11 +685,12 @@ class HasManyAssociationsTest < ActiveRecord::TestCase client_id = firm.clients_of_firm.first.id assert_equal 1, firm.clients_of_firm.size - firm.clients_of_firm.clear + cleared = firm.clients_of_firm.clear assert_equal 0, firm.clients_of_firm.size assert_equal 0, firm.clients_of_firm(true).size assert_equal [], Client.destroyed_client_ids[firm.id] + assert_equal firm.clients_of_firm.object_id, cleared.object_id # Should not be destroyed since the association is not dependent. assert_nothing_raised do -- cgit v1.2.3 From 3fa61ccb9eed0f17cdef85470ae708b4b09a3c06 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Wed, 26 Jan 2011 23:00:13 +0000 Subject: Has many through - It is not necessary to manually merge in the conditions hash for the through record, because the creation is done directly on the through association, which will already handle setting the conditions. --- .../cases/associations/has_many_through_associations_test.rb | 12 +++++++++++- activerecord/test/models/club.rb | 3 ++- activerecord/test/models/member.rb | 3 +++ 3 files changed, 16 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 7235631b5a..96f4597726 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -20,10 +20,13 @@ require 'models/subscription' require 'models/categorization' require 'models/category' require 'models/essay' +require 'models/member' +require 'models/membership' +require 'models/club' class HasManyThroughAssociationsTest < ActiveRecord::TestCase fixtures :posts, :readers, :people, :comments, :authors, :categories, - :owners, :pets, :toys, :jobs, :references, :companies, + :owners, :pets, :toys, :jobs, :references, :companies, :members, :subscribers, :books, :subscriptions, :developers, :categorizations # Dummies to force column loads so query counts are clean. @@ -557,4 +560,11 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase assert proxy.stale_target? assert_equal authors(:david).categorizations.sort_by(&:id), post.author_categorizations.sort_by(&:id) end + + def test_create_with_conditions_hash_on_through_association + member = members(:groucho) + club = member.clubs.create! + + assert_equal true, club.reload.membership.favourite + end end diff --git a/activerecord/test/models/club.rb b/activerecord/test/models/club.rb index 6e7cdd643a..c432a6ace8 100644 --- a/activerecord/test/models/club.rb +++ b/activerecord/test/models/club.rb @@ -1,4 +1,5 @@ class Club < ActiveRecord::Base + has_one :membership has_many :memberships has_many :members, :through => :memberships has_many :current_memberships @@ -10,4 +11,4 @@ class Club < ActiveRecord::Base def private_method "I'm sorry sir, this is a *private* club, not a *pirate* club" end -end \ No newline at end of file +end diff --git a/activerecord/test/models/member.rb b/activerecord/test/models/member.rb index 15ad6aedd3..e6e78f9e45 100644 --- a/activerecord/test/models/member.rb +++ b/activerecord/test/models/member.rb @@ -13,4 +13,7 @@ class Member < ActiveRecord::Base has_many :current_memberships has_one :club_through_many, :through => :current_memberships, :source => :club + + has_many :current_memberships, :conditions => { :favourite => true } + has_many :clubs, :through => :current_memberships end -- cgit v1.2.3 From 30176f28a41681c7607eed39d03501327869d40c Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Mon, 31 Jan 2011 13:21:03 +0000 Subject: Add :bulk => true option to change_table --- .../test/cases/migration/command_recorder_test.rb | 2 +- activerecord/test/cases/migration_test.rb | 138 +++++++++++++++++++++ 2 files changed, 139 insertions(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/migration/command_recorder_test.rb b/activerecord/test/cases/migration/command_recorder_test.rb index ea2292dda5..ae531ebb4c 100644 --- a/activerecord/test/cases/migration/command_recorder_test.rb +++ b/activerecord/test/cases/migration/command_recorder_test.rb @@ -16,7 +16,7 @@ module ActiveRecord def test_send_calls_super assert_raises(NoMethodError) do - @recorder.send(:create_table, :horses) + @recorder.send(:non_existing_method, :horses) end end diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index a5a9965c3a..c2a80b02b6 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -1923,6 +1923,144 @@ if ActiveRecord::Base.connection.supports_migrations? end end + class AlterTableMigrationsTest < ActiveRecord::TestCase + def setup + @connection = Person.connection + @connection.create_table(:delete_me, :force => true) {|t| } + end + + def teardown + Person.connection.drop_table(:delete_me) rescue nil + end + + def test_adding_multiple_columns + assert_queries(1) do + with_bulk_change_table do |t| + t.column :name, :string + t.string :qualification, :experience + t.integer :age, :default => 0 + t.date :birthdate + t.timestamps + end + end + + assert_equal 8, columns.size + [:name, :qualification, :experience].each {|s| assert_equal :string, column(s).type } + assert_equal 0, column(:age).default + end + + def test_removing_columns + with_bulk_change_table do |t| + t.string :qualification, :experience + end + + [:qualification, :experience].each {|c| assert column(c) } + + assert_queries(1) do + with_bulk_change_table do |t| + t.remove :qualification, :experience + t.string :qualification_experience + end + end + + [:qualification, :experience].each {|c| assert ! column(c) } + assert column(:qualification_experience) + end + + def test_adding_indexes + with_bulk_change_table do |t| + t.string :username + t.string :name + t.integer :age + end + + # Adding an index fires a query everytime to check if an index already exists or not + assert_queries(3) do + with_bulk_change_table do |t| + t.index :username, :unique => true, :name => :awesome_username_index + t.index [:name, :age] + end + end + + assert_equal 2, indexes.size + + name_age_index = index(:index_delete_me_on_name_and_age) + assert_equal ['name', 'age'].sort, name_age_index.columns.sort + assert ! name_age_index.unique + + assert index(:awesome_username_index).unique + end + + def test_removing_index + with_bulk_change_table do |t| + t.string :name + t.index :name + end + + assert index(:index_delete_me_on_name) + + assert_queries(3) do + with_bulk_change_table do |t| + t.remove_index :name + t.index :name, :name => :new_name_index, :unique => true + end + end + + assert ! index(:index_delete_me_on_name) + + new_name_index = index(:new_name_index) + assert new_name_index.unique + end + + def test_changing_columns + with_bulk_change_table do |t| + t.string :name + t.date :birthdate + end + + assert ! column(:name).default + assert_equal :date, column(:birthdate).type + + assert_queries(1) do + with_bulk_change_table do |t| + t.change :name, :string, :default => 'NONAME' + t.change :birthdate, :datetime + end + end + + assert_equal 'NONAME', column(:name).default + assert_equal :datetime, column(:birthdate).type + end + + protected + + def with_bulk_change_table + # Reset columns/indexes cache as we're changing the table + @columns = @indexes = nil + + Person.connection.change_table(:delete_me, :bulk => true) do |t| + yield t + end + end + + def column(name) + columns.detect {|c| c.name == name.to_s } + end + + def columns + @columns ||= Person.connection.columns('delete_me') + end + + def index(name) + indexes.detect {|i| i.name == name.to_s } + end + + def indexes + @indexes ||= Person.connection.indexes('delete_me') + end + + end + class CopyMigrationsTest < ActiveRecord::TestCase def setup end -- cgit v1.2.3 From 9666b6a625c9fef555c2a18df6721fed2000f131 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Mon, 31 Jan 2011 14:10:51 +0000 Subject: Run BulkAlterTableMigrationsTest only when the adapter supports them --- activerecord/test/cases/migration_test.rb | 196 +++++++++++++++--------------- 1 file changed, 99 insertions(+), 97 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index c2a80b02b6..6f0f73e3bd 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -1923,141 +1923,143 @@ if ActiveRecord::Base.connection.supports_migrations? end end - class AlterTableMigrationsTest < ActiveRecord::TestCase - def setup - @connection = Person.connection - @connection.create_table(:delete_me, :force => true) {|t| } - end - - def teardown - Person.connection.drop_table(:delete_me) rescue nil - end + if ActiveRecord::Base.connection.supports_bulk_alter? + class BulkAlterTableMigrationsTest < ActiveRecord::TestCase + def setup + @connection = Person.connection + @connection.create_table(:delete_me, :force => true) {|t| } + end - def test_adding_multiple_columns - assert_queries(1) do - with_bulk_change_table do |t| - t.column :name, :string - t.string :qualification, :experience - t.integer :age, :default => 0 - t.date :birthdate - t.timestamps - end + def teardown + Person.connection.drop_table(:delete_me) rescue nil end - assert_equal 8, columns.size - [:name, :qualification, :experience].each {|s| assert_equal :string, column(s).type } - assert_equal 0, column(:age).default - end + def test_adding_multiple_columns + assert_queries(1) do + with_bulk_change_table do |t| + t.column :name, :string + t.string :qualification, :experience + t.integer :age, :default => 0 + t.date :birthdate + t.timestamps + end + end - def test_removing_columns - with_bulk_change_table do |t| - t.string :qualification, :experience + assert_equal 8, columns.size + [:name, :qualification, :experience].each {|s| assert_equal :string, column(s).type } + assert_equal 0, column(:age).default end - [:qualification, :experience].each {|c| assert column(c) } - - assert_queries(1) do + def test_removing_columns with_bulk_change_table do |t| - t.remove :qualification, :experience - t.string :qualification_experience + t.string :qualification, :experience end - end - [:qualification, :experience].each {|c| assert ! column(c) } - assert column(:qualification_experience) - end + [:qualification, :experience].each {|c| assert column(c) } - def test_adding_indexes - with_bulk_change_table do |t| - t.string :username - t.string :name - t.integer :age + assert_queries(1) do + with_bulk_change_table do |t| + t.remove :qualification, :experience + t.string :qualification_experience + end + end + + [:qualification, :experience].each {|c| assert ! column(c) } + assert column(:qualification_experience) end - # Adding an index fires a query everytime to check if an index already exists or not - assert_queries(3) do + def test_adding_indexes with_bulk_change_table do |t| - t.index :username, :unique => true, :name => :awesome_username_index - t.index [:name, :age] + t.string :username + t.string :name + t.integer :age end - end - assert_equal 2, indexes.size + # Adding an index fires a query everytime to check if an index already exists or not + assert_queries(3) do + with_bulk_change_table do |t| + t.index :username, :unique => true, :name => :awesome_username_index + t.index [:name, :age] + end + end - name_age_index = index(:index_delete_me_on_name_and_age) - assert_equal ['name', 'age'].sort, name_age_index.columns.sort - assert ! name_age_index.unique + assert_equal 2, indexes.size - assert index(:awesome_username_index).unique - end + name_age_index = index(:index_delete_me_on_name_and_age) + assert_equal ['name', 'age'].sort, name_age_index.columns.sort + assert ! name_age_index.unique - def test_removing_index - with_bulk_change_table do |t| - t.string :name - t.index :name + assert index(:awesome_username_index).unique end - assert index(:index_delete_me_on_name) - - assert_queries(3) do + def test_removing_index with_bulk_change_table do |t| - t.remove_index :name - t.index :name, :name => :new_name_index, :unique => true + t.string :name + t.index :name end - end - assert ! index(:index_delete_me_on_name) + assert index(:index_delete_me_on_name) - new_name_index = index(:new_name_index) - assert new_name_index.unique - end + assert_queries(3) do + with_bulk_change_table do |t| + t.remove_index :name + t.index :name, :name => :new_name_index, :unique => true + end + end - def test_changing_columns - with_bulk_change_table do |t| - t.string :name - t.date :birthdate - end + assert ! index(:index_delete_me_on_name) - assert ! column(:name).default - assert_equal :date, column(:birthdate).type + new_name_index = index(:new_name_index) + assert new_name_index.unique + end - assert_queries(1) do + def test_changing_columns with_bulk_change_table do |t| - t.change :name, :string, :default => 'NONAME' - t.change :birthdate, :datetime + t.string :name + t.date :birthdate end - end - assert_equal 'NONAME', column(:name).default - assert_equal :datetime, column(:birthdate).type - end + assert ! column(:name).default + assert_equal :date, column(:birthdate).type - protected + assert_queries(1) do + with_bulk_change_table do |t| + t.change :name, :string, :default => 'NONAME' + t.change :birthdate, :datetime + end + end + + assert_equal 'NONAME', column(:name).default + assert_equal :datetime, column(:birthdate).type + end - def with_bulk_change_table - # Reset columns/indexes cache as we're changing the table - @columns = @indexes = nil + protected - Person.connection.change_table(:delete_me, :bulk => true) do |t| - yield t + def with_bulk_change_table + # Reset columns/indexes cache as we're changing the table + @columns = @indexes = nil + + Person.connection.change_table(:delete_me, :bulk => true) do |t| + yield t + end end - end - def column(name) - columns.detect {|c| c.name == name.to_s } - end + def column(name) + columns.detect {|c| c.name == name.to_s } + end - def columns - @columns ||= Person.connection.columns('delete_me') - end + def columns + @columns ||= Person.connection.columns('delete_me') + end - def index(name) - indexes.detect {|i| i.name == name.to_s } - end + def index(name) + indexes.detect {|i| i.name == name.to_s } + end - def indexes - @indexes ||= Person.connection.indexes('delete_me') - end + def indexes + @indexes ||= Person.connection.indexes('delete_me') + end + end # AlterTableMigrationsTest end -- cgit v1.2.3 From 817e37013610c8e8866197594d5e408b4d5daec5 Mon Sep 17 00:00:00 2001 From: Akira Matsuda Date: Thu, 16 Dec 2010 18:31:31 +0900 Subject: Make before_type_cast available for datetime fields [#3973 state:committed] Signed-off-by: Santiago Pastorino --- activerecord/test/cases/attribute_methods_test.rb | 31 +++++++++++------------ 1 file changed, 15 insertions(+), 16 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb index a29e4349d6..06adb33ffc 100644 --- a/activerecord/test/cases/attribute_methods_test.rb +++ b/activerecord/test/cases/attribute_methods_test.rb @@ -116,24 +116,23 @@ class AttributeMethodsTest < ActiveRecord::TestCase end end - unless current_adapter?(:Mysql2Adapter) - def test_read_attributes_before_type_cast_on_datetime - developer = Developer.find(:first) - # Oracle adapter returns Time before type cast - unless current_adapter?(:OracleAdapter) - assert_equal developer.created_at.to_s(:db) , developer.attributes_before_type_cast["created_at"].to_s - else - assert_equal developer.created_at.to_s(:db) , developer.attributes_before_type_cast["created_at"].to_s(:db) + def test_read_attributes_before_type_cast_on_datetime + developer = Developer.find(:first) + if current_adapter?(:Mysql2Adapter) + # Mysql2 keeps the value in Time instance + assert_equal developer.created_at.to_s(:db), developer.attributes_before_type_cast["created_at"].to_s(:db) + else + assert_equal developer.created_at.to_s(:db), developer.attributes_before_type_cast["created_at"].to_s + end - developer.created_at = "345643456" - assert_equal developer.created_at_before_type_cast, "345643456" - assert_equal developer.created_at, nil + developer.created_at = "345643456" - developer.created_at = "2010-03-21 21:23:32" - assert_equal developer.created_at_before_type_cast.to_s, "2010-03-21 21:23:32" - assert_equal developer.created_at, Time.parse("2010-03-21 21:23:32") - end - end + assert_equal developer.created_at_before_type_cast, "345643456" + assert_equal developer.created_at, nil + + developer.created_at = "2010-03-21 21:23:32" + assert_equal developer.created_at_before_type_cast.to_s, "2010-03-21 21:23:32" + assert_equal developer.created_at, Time.parse("2010-03-21 21:23:32") end def test_hash_content -- cgit v1.2.3 From 6bd9fac1e301d57765073e1f7a17e46972428205 Mon Sep 17 00:00:00 2001 From: Glenn Vanderburg Date: Fri, 28 Jan 2011 18:16:44 -0600 Subject: Propagate association extensions to scopes called on the association. Signed-off-by: Santiago Pastorino --- activerecord/test/cases/associations/extension_test.rb | 5 +++++ activerecord/test/models/comment.rb | 1 + 2 files changed, 6 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/extension_test.rb b/activerecord/test/cases/associations/extension_test.rb index efaab8569e..e1f5b16eca 100644 --- a/activerecord/test/cases/associations/extension_test.rb +++ b/activerecord/test/cases/associations/extension_test.rb @@ -29,6 +29,11 @@ class AssociationsExtensionsTest < ActiveRecord::TestCase assert_equal projects(:action_controller), developers(:david).projects_extended_by_name_and_block.find_most_recent assert_equal projects(:active_record), developers(:david).projects_extended_by_name_and_block.find_least_recent end + + def test_extension_with_scopes + assert_equal comments(:greetings), posts(:welcome).comments.offset(1).find_most_recent + assert_equal comments(:greetings), posts(:welcome).comments.not_again.find_most_recent + end def test_marshalling_extensions david = developers(:david) diff --git a/activerecord/test/models/comment.rb b/activerecord/test/models/comment.rb index a9aa0afced..ff533717cc 100644 --- a/activerecord/test/models/comment.rb +++ b/activerecord/test/models/comment.rb @@ -1,6 +1,7 @@ class Comment < ActiveRecord::Base scope :limit_by, lambda {|l| limit(l) } scope :containing_the_letter_e, :conditions => "comments.body LIKE '%e%'" + scope :not_again, where("comments.body NOT LIKE '%again%'") scope :for_first_post, :conditions => { :post_id => 1 } scope :for_first_author, :joins => :post, -- cgit v1.2.3 From 6d5e3b86d581c109ad60fe771de0ac852f1af259 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 31 Jan 2011 14:38:20 -0800 Subject: namespace test so we can dry up constant lookup --- activerecord/test/cases/column_definition_test.rb | 194 +++++++++++----------- 1 file changed, 99 insertions(+), 95 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/column_definition_test.rb b/activerecord/test/cases/column_definition_test.rb index cc6a6b44f2..f87f819812 100644 --- a/activerecord/test/cases/column_definition_test.rb +++ b/activerecord/test/cases/column_definition_test.rb @@ -1,121 +1,125 @@ require "cases/helper" -class ColumnDefinitionTest < ActiveRecord::TestCase - def setup - @adapter = ActiveRecord::ConnectionAdapters::AbstractAdapter.new(nil) - def @adapter.native_database_types - {:string => "varchar"} - end - end - - # Avoid column definitions in create table statements like: - # `title` varchar(255) DEFAULT NULL - def test_should_not_include_default_clause_when_default_is_null - column = ActiveRecord::ConnectionAdapters::Column.new("title", nil, "varchar(20)") - column_def = ActiveRecord::ConnectionAdapters::ColumnDefinition.new( - @adapter, column.name, "string", - column.limit, column.precision, column.scale, column.default, column.null) - assert_equal "title varchar(20)", column_def.to_sql - end - - def test_should_include_default_clause_when_default_is_present - column = ActiveRecord::ConnectionAdapters::Column.new("title", "Hello", "varchar(20)") - column_def = ActiveRecord::ConnectionAdapters::ColumnDefinition.new( - @adapter, column.name, "string", - column.limit, column.precision, column.scale, column.default, column.null) - assert_equal %Q{title varchar(20) DEFAULT 'Hello'}, column_def.to_sql - end - - def test_should_specify_not_null_if_null_option_is_false - column = ActiveRecord::ConnectionAdapters::Column.new("title", "Hello", "varchar(20)", false) - column_def = ActiveRecord::ConnectionAdapters::ColumnDefinition.new( - @adapter, column.name, "string", - column.limit, column.precision, column.scale, column.default, column.null) - assert_equal %Q{title varchar(20) DEFAULT 'Hello' NOT NULL}, column_def.to_sql - end - - if current_adapter?(:MysqlAdapter) - def test_should_set_default_for_mysql_binary_data_types - binary_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", "a", "binary(1)") - assert_equal "a", binary_column.default +module ActiveRecord + module ConnectionAdapters + class ColumnDefinitionTest < ActiveRecord::TestCase + def setup + @adapter = AbstractAdapter.new(nil) + def @adapter.native_database_types + {:string => "varchar"} + end + end - varbinary_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", "a", "varbinary(1)") - assert_equal "a", varbinary_column.default - end + # Avoid column definitions in create table statements like: + # `title` varchar(255) DEFAULT NULL + def test_should_not_include_default_clause_when_default_is_null + column = Column.new("title", nil, "varchar(20)") + column_def = ColumnDefinition.new( + @adapter, column.name, "string", + column.limit, column.precision, column.scale, column.default, column.null) + assert_equal "title varchar(20)", column_def.to_sql + end - def test_should_not_set_default_for_blob_and_text_data_types - assert_raise ArgumentError do - ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", "a", "blob") + def test_should_include_default_clause_when_default_is_present + column = Column.new("title", "Hello", "varchar(20)") + column_def = ColumnDefinition.new( + @adapter, column.name, "string", + column.limit, column.precision, column.scale, column.default, column.null) + assert_equal %Q{title varchar(20) DEFAULT 'Hello'}, column_def.to_sql end - assert_raise ArgumentError do - ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", "Hello", "text") + def test_should_specify_not_null_if_null_option_is_false + column = Column.new("title", "Hello", "varchar(20)", false) + column_def = ColumnDefinition.new( + @adapter, column.name, "string", + column.limit, column.precision, column.scale, column.default, column.null) + assert_equal %Q{title varchar(20) DEFAULT 'Hello' NOT NULL}, column_def.to_sql end - text_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", nil, "text") - assert_equal nil, text_column.default + if current_adapter?(:MysqlAdapter) + def test_should_set_default_for_mysql_binary_data_types + binary_column = MysqlColumn.new("title", "a", "binary(1)") + assert_equal "a", binary_column.default - not_null_text_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", nil, "text", false) - assert_equal "", not_null_text_column.default - end + varbinary_column = MysqlColumn.new("title", "a", "varbinary(1)") + assert_equal "a", varbinary_column.default + end - def test_has_default_should_return_false_for_blog_and_test_data_types - blob_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", nil, "blob") - assert !blob_column.has_default? + def test_should_not_set_default_for_blob_and_text_data_types + assert_raise ArgumentError do + MysqlColumn.new("title", "a", "blob") + end - text_column = ActiveRecord::ConnectionAdapters::MysqlColumn.new("title", nil, "text") - assert !text_column.has_default? - end - end + assert_raise ArgumentError do + MysqlColumn.new("title", "Hello", "text") + end - if current_adapter?(:Mysql2Adapter) - def test_should_set_default_for_mysql_binary_data_types - binary_column = ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", "a", "binary(1)") - assert_equal "a", binary_column.default + text_column = MysqlColumn.new("title", nil, "text") + assert_equal nil, text_column.default - varbinary_column = ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", "a", "varbinary(1)") - assert_equal "a", varbinary_column.default - end + not_null_text_column = MysqlColumn.new("title", nil, "text", false) + assert_equal "", not_null_text_column.default + end - def test_should_not_set_default_for_blob_and_text_data_types - assert_raise ArgumentError do - ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", "a", "blob") - end + def test_has_default_should_return_false_for_blog_and_test_data_types + blob_column = MysqlColumn.new("title", nil, "blob") + assert !blob_column.has_default? - assert_raise ArgumentError do - ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", "Hello", "text") + text_column = MysqlColumn.new("title", nil, "text") + assert !text_column.has_default? + end end - text_column = ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", nil, "text") - assert_equal nil, text_column.default + if current_adapter?(:Mysql2Adapter) + def test_should_set_default_for_mysql_binary_data_types + binary_column = Mysql2Column.new("title", "a", "binary(1)") + assert_equal "a", binary_column.default - not_null_text_column = ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", nil, "text", false) - assert_equal "", not_null_text_column.default - end + varbinary_column = Mysql2Column.new("title", "a", "varbinary(1)") + assert_equal "a", varbinary_column.default + end - def test_has_default_should_return_false_for_blog_and_test_data_types - blob_column = ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", nil, "blob") - assert !blob_column.has_default? + def test_should_not_set_default_for_blob_and_text_data_types + assert_raise ArgumentError do + Mysql2Column.new("title", "a", "blob") + end - text_column = ActiveRecord::ConnectionAdapters::Mysql2Column.new("title", nil, "text") - assert !text_column.has_default? - end - end + assert_raise ArgumentError do + Mysql2Column.new("title", "Hello", "text") + end - if current_adapter?(:PostgreSQLAdapter) - def test_bigint_column_should_map_to_integer - bigint_column = ActiveRecord::ConnectionAdapters::PostgreSQLColumn.new('number', nil, "bigint") - assert_equal :integer, bigint_column.type - end + text_column = Mysql2Column.new("title", nil, "text") + assert_equal nil, text_column.default - def test_smallint_column_should_map_to_integer - smallint_column = ActiveRecord::ConnectionAdapters::PostgreSQLColumn.new('number', nil, "smallint") - assert_equal :integer, smallint_column.type - end + not_null_text_column = Mysql2Column.new("title", nil, "text", false) + assert_equal "", not_null_text_column.default + end + + def test_has_default_should_return_false_for_blog_and_test_data_types + blob_column = Mysql2Column.new("title", nil, "blob") + assert !blob_column.has_default? - def test_uuid_column_should_map_to_string - uuid_column = ActiveRecord::ConnectionAdapters::PostgreSQLColumn.new('unique_id', nil, "uuid") - assert_equal :string, uuid_column.type + text_column = Mysql2Column.new("title", nil, "text") + assert !text_column.has_default? + end + end + + if current_adapter?(:PostgreSQLAdapter) + def test_bigint_column_should_map_to_integer + bigint_column = PostgreSQLColumn.new('number', nil, "bigint") + assert_equal :integer, bigint_column.type + end + + def test_smallint_column_should_map_to_integer + smallint_column = PostgreSQLColumn.new('number', nil, "smallint") + assert_equal :integer, smallint_column.type + end + + def test_uuid_column_should_map_to_string + uuid_column = PostgreSQLColumn.new('unique_id', nil, "uuid") + assert_equal :string, uuid_column.type + end + end end end end -- cgit v1.2.3 From a7c2f6be3050b035865a48accb102568c961c1bf Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 31 Jan 2011 14:47:21 -0800 Subject: coders can be assigned to columns --- activerecord/test/cases/column_definition_test.rb | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/column_definition_test.rb b/activerecord/test/cases/column_definition_test.rb index f87f819812..a80deee93e 100644 --- a/activerecord/test/cases/column_definition_test.rb +++ b/activerecord/test/cases/column_definition_test.rb @@ -10,6 +10,20 @@ module ActiveRecord end end + def test_can_set_coder + column = Column.new("title", nil, "varchar(20)") + column.coder = YAML + assert_equal YAML, column.coder + end + + def test_encoded? + column = Column.new("title", nil, "varchar(20)") + assert !column.encoded? + + column.coder = YAML + assert column.encoded? + end + # Avoid column definitions in create table statements like: # `title` varchar(255) DEFAULT NULL def test_should_not_include_default_clause_when_default_is_null -- cgit v1.2.3 From 65f11ff7894ace0e762921a36489de46bd22c724 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 31 Jan 2011 15:10:32 -0800 Subject: column will use coder to typecase value when it is available --- activerecord/test/cases/column_definition_test.rb | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/column_definition_test.rb b/activerecord/test/cases/column_definition_test.rb index a80deee93e..d1dddd4c2c 100644 --- a/activerecord/test/cases/column_definition_test.rb +++ b/activerecord/test/cases/column_definition_test.rb @@ -24,6 +24,12 @@ module ActiveRecord assert column.encoded? end + def test_type_case_coded_column + column = Column.new("title", nil, "varchar(20)") + column.coder = YAML + assert_equal "hello", column.type_cast("--- hello") + end + # Avoid column definitions in create table statements like: # `title` varchar(255) DEFAULT NULL def test_should_not_include_default_clause_when_default_is_null -- cgit v1.2.3 From 3cc2b77dc1cb4c1e5cfac68c7828e35a27415e0d Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 1 Feb 2011 09:34:21 -0800 Subject: adding a YAML Column coder for YAML serialization to db columns --- activerecord/test/cases/coders/yaml_column_test.rb | 45 ++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 activerecord/test/cases/coders/yaml_column_test.rb (limited to 'activerecord/test') diff --git a/activerecord/test/cases/coders/yaml_column_test.rb b/activerecord/test/cases/coders/yaml_column_test.rb new file mode 100644 index 0000000000..f85f11b57f --- /dev/null +++ b/activerecord/test/cases/coders/yaml_column_test.rb @@ -0,0 +1,45 @@ +require "cases/helper" + +module ActiveRecord + module Coders + class YAMLColumnTest < ActiveRecord::TestCase + def test_initialize_takes_class + coder = YAMLColumn.new(Object) + assert_equal Object, coder.object_class + end + + def test_type_mismatch_on_different_classes + coder = YAMLColumn.new(Array) + assert_raises(SerializationTypeMismatch) do + coder.load "--- foo" + end + end + + def test_nil_is_ok + coder = YAMLColumn.new + assert_nil coder.load "--- " + end + + def test_nil_is_ok_with_different_class + coder = YAMLColumn.new SerializationTypeMismatch + assert_nil coder.load "--- " + end + + def test_returns_string_unless_starts_with_dash + coder = YAMLColumn.new + assert_equal 'foo', coder.load("foo") + end + + def test_load_handles_other_classes + coder = YAMLColumn.new + assert_equal [], coder.load([]) + end + + def test_load_swallows_yaml_exceptions + coder = YAMLColumn.new + bad_yaml = '--- {' + assert_equal bad_yaml, coder.load(bad_yaml) + end + end + end +end -- cgit v1.2.3 From ee34b4cf346975d0aef7f26ef47ee2e4f3e13c37 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 1 Feb 2011 11:30:09 -0800 Subject: share column cache among subclasses, only look up columns per AR::Base subclass once --- activerecord/test/cases/session_store/session_test.rb | 1 + activerecord/test/models/contact.rb | 4 ++++ 2 files changed, 5 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/session_store/session_test.rb b/activerecord/test/cases/session_store/session_test.rb index f906bda8c3..cee5ddd003 100644 --- a/activerecord/test/cases/session_store/session_test.rb +++ b/activerecord/test/cases/session_store/session_test.rb @@ -60,6 +60,7 @@ module ActiveRecord end def test_loaded? + Session.create_table! s = Session.new assert !s.loaded?, 'session is not loaded' end diff --git a/activerecord/test/models/contact.rb b/activerecord/test/models/contact.rb index 975a885331..5bbe7ebb12 100644 --- a/activerecord/test/models/contact.rb +++ b/activerecord/test/models/contact.rb @@ -1,4 +1,8 @@ class Contact < ActiveRecord::Base + def self.columns + @columns + end + # mock out self.columns so no pesky db is needed for these tests def self.column(name, sql_type = nil, options = {}) @columns ||= [] -- cgit v1.2.3 From ebe485fd8ec80a1a9b86516bc6f74bc5bbba3476 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 1 Feb 2011 11:41:14 -0800 Subject: serialize can take an arbitrary code object --- activerecord/test/cases/base_test.rb | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index a58d5dec81..7c677d55ca 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -1018,6 +1018,27 @@ class BasicsTest < ActiveRecord::TestCase assert_equal topic.content, false end + def test_serialize_with_coder + coder = Class.new { + # Identity + def load(thing) + thing + end + + # base 64 + def dump(thing) + [thing].pack('m') + end + }.new + + Topic.serialize(:content, coder) + s = 'hello world' + topic = Topic.new(:content => s) + assert topic.save + topic = topic.reload + assert_equal [s].pack('m'), topic.content + end + def test_quote author_name = "\\ \001 ' \n \\n \"" topic = Topic.create('author_name' => author_name) -- cgit v1.2.3 From a0fac7192241f3242af410ca16e6dd43b933c98e Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 1 Feb 2011 14:25:33 -0800 Subject: store the serialized column values in the @attributes hash --- activerecord/test/cases/base_test.rb | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 7c677d55ca..5cbc52732b 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -1037,6 +1037,31 @@ class BasicsTest < ActiveRecord::TestCase assert topic.save topic = topic.reload assert_equal [s].pack('m'), topic.content + ensure + Topic.serialize(:content) + end + + def test_serialize_with_bcrypt_coder + crypt_coder = Class.new { + def load(thing) + return unless thing + BCrypt::Password.new thing + end + + def dump(thing) + BCrypt::Password.create(thing).to_s + end + }.new + + Topic.serialize(:content, crypt_coder) + password = 'password' + topic = Topic.new(:content => password) + assert topic.save + topic = topic.reload + assert_kind_of BCrypt::Password, topic.content + assert_equal(true, topic.content == password, 'password should equal') + ensure + Topic.serialize(:content) end def test_quote -- cgit v1.2.3 From 5b42e9660201fc721075d2bfbe13edb0014dbde2 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 1 Feb 2011 15:23:55 -0800 Subject: make sure de-serialization happens on object instantiation --- activerecord/test/cases/serialization_test.rb | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/serialization_test.rb b/activerecord/test/cases/serialization_test.rb index 25dbcc9fc2..677d659f39 100644 --- a/activerecord/test/cases/serialization_test.rb +++ b/activerecord/test/cases/serialization_test.rb @@ -23,6 +23,12 @@ class SerializationTest < ActiveRecord::TestCase @contact = Contact.new(@contact_attributes) end + def test_serialized_init_with + topic = Topic.allocate + topic.init_with('attributes' => { 'content' => '--- foo' }) + assert_equal 'foo', topic.content + end + def test_to_xml xml = REXML::Document.new(topics(:first).to_xml(:indent => 0)) bonus_time_in_current_timezone = topics(:first).bonus_time.xmlschema -- cgit v1.2.3 From 6d40d527e896038767272eca3a6357e6998b985e Mon Sep 17 00:00:00 2001 From: Franck Verrot Date: Tue, 25 Jan 2011 23:20:57 +0100 Subject: Test private method timestamp_attributes_for_create Signed-off-by: Santiago Pastorino --- activerecord/test/cases/timestamp_test.rb | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb index 70c098bc6d..1970bf0a5d 100644 --- a/activerecord/test/cases/timestamp_test.rb +++ b/activerecord/test/cases/timestamp_test.rb @@ -140,4 +140,9 @@ class TimestampTest < ActiveRecord::TestCase ensure Toy.belongs_to :pet end + + def test_timestamp_attributes_for_create + toy = Toy.first + assert_equal toy.send(:timestamp_attributes_for_create), [:created_at, :created_on] + end end -- cgit v1.2.3 From 253f5a15f42720ddc2cf6cd7e982fe3e0dc65f52 Mon Sep 17 00:00:00 2001 From: Franck Verrot Date: Tue, 25 Jan 2011 23:21:33 +0100 Subject: Test private method timestamp_attributes_for_update Signed-off-by: Santiago Pastorino --- activerecord/test/cases/timestamp_test.rb | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb index 1970bf0a5d..26c04c47b9 100644 --- a/activerecord/test/cases/timestamp_test.rb +++ b/activerecord/test/cases/timestamp_test.rb @@ -145,4 +145,9 @@ class TimestampTest < ActiveRecord::TestCase toy = Toy.first assert_equal toy.send(:timestamp_attributes_for_create), [:created_at, :created_on] end + + def test_timestamp_attributes_for_update + toy = Toy.first + assert_equal toy.send(:timestamp_attributes_for_update), [:updated_at, :updated_on] + end end -- cgit v1.2.3 From 598b32c5812e428f639c9a80b352aec54f059a36 Mon Sep 17 00:00:00 2001 From: Franck Verrot Date: Tue, 25 Jan 2011 23:23:19 +0100 Subject: Test private method all_timestamp_attributes Signed-off-by: Santiago Pastorino --- activerecord/test/cases/timestamp_test.rb | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb index 26c04c47b9..006266536c 100644 --- a/activerecord/test/cases/timestamp_test.rb +++ b/activerecord/test/cases/timestamp_test.rb @@ -150,4 +150,9 @@ class TimestampTest < ActiveRecord::TestCase toy = Toy.first assert_equal toy.send(:timestamp_attributes_for_update), [:updated_at, :updated_on] end + + def test_all_timestamp_attributes + toy = Toy.first + assert_equal toy.send(:all_timestamp_attributes), [:created_at, :created_on, :updated_at, :updated_on] + end end -- cgit v1.2.3 From 5178e641750d4e3f8419c8e6cf3ab7e7cb48a880 Mon Sep 17 00:00:00 2001 From: Franck Verrot Date: Tue, 25 Jan 2011 23:27:27 +0100 Subject: Added timestamp_attributes_for_create_in_model Signed-off-by: Santiago Pastorino --- activerecord/test/cases/timestamp_test.rb | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb index 006266536c..428dfedef2 100644 --- a/activerecord/test/cases/timestamp_test.rb +++ b/activerecord/test/cases/timestamp_test.rb @@ -155,4 +155,9 @@ class TimestampTest < ActiveRecord::TestCase toy = Toy.first assert_equal toy.send(:all_timestamp_attributes), [:created_at, :created_on, :updated_at, :updated_on] end + + def test_timestamp_attributes_for_create_in_model + toy = Toy.first + assert_equal toy.send(:timestamp_attributes_for_create_in_model), [:created_at] + end end -- cgit v1.2.3 From 47315760bc893a48738e6592a0cbb3fef506bcd7 Mon Sep 17 00:00:00 2001 From: Franck Verrot Date: Tue, 25 Jan 2011 23:28:31 +0100 Subject: Test timestamp_attributes_for_update_in_model that was already in place Signed-off-by: Santiago Pastorino --- activerecord/test/cases/timestamp_test.rb | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb index 428dfedef2..62e3a084d0 100644 --- a/activerecord/test/cases/timestamp_test.rb +++ b/activerecord/test/cases/timestamp_test.rb @@ -160,4 +160,9 @@ class TimestampTest < ActiveRecord::TestCase toy = Toy.first assert_equal toy.send(:timestamp_attributes_for_create_in_model), [:created_at] end + + def test_timestamp_attributes_for_update_in_model + toy = Toy.first + assert_equal toy.send(:timestamp_attributes_for_update_in_model), [:updated_at] + end end -- cgit v1.2.3 From a5b03e9c7af8f539764a66f9bd51b7ebbcb9f57d Mon Sep 17 00:00:00 2001 From: Franck Verrot Date: Tue, 25 Jan 2011 23:33:55 +0100 Subject: Implement and test private method all_timestamp_attributes_in_model Signed-off-by: Santiago Pastorino --- activerecord/test/cases/timestamp_test.rb | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb index 62e3a084d0..1c21f0f3b6 100644 --- a/activerecord/test/cases/timestamp_test.rb +++ b/activerecord/test/cases/timestamp_test.rb @@ -165,4 +165,9 @@ class TimestampTest < ActiveRecord::TestCase toy = Toy.first assert_equal toy.send(:timestamp_attributes_for_update_in_model), [:updated_at] end + + def test_all_timestamp_attributes_in_model + toy = Toy.first + assert_equal toy.send(:all_timestamp_attributes_in_model), [:created_at, :updated_at] + end end -- cgit v1.2.3 From 9e23835cb8f6b9284d635e52f7e374563ea51042 Mon Sep 17 00:00:00 2001 From: Raimonds Simanovskis Date: Wed, 2 Feb 2011 17:45:12 +0100 Subject: fix for test_read_attributes_before_type_cast_on_datetime - Oracle adapter also returns Time value --- activerecord/test/cases/attribute_methods_test.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb index 06adb33ffc..7e3e204626 100644 --- a/activerecord/test/cases/attribute_methods_test.rb +++ b/activerecord/test/cases/attribute_methods_test.rb @@ -118,8 +118,8 @@ class AttributeMethodsTest < ActiveRecord::TestCase def test_read_attributes_before_type_cast_on_datetime developer = Developer.find(:first) - if current_adapter?(:Mysql2Adapter) - # Mysql2 keeps the value in Time instance + if current_adapter?(:Mysql2Adapter, :OracleAdapter) + # Mysql2 and Oracle adapters keep the value in Time instance assert_equal developer.created_at.to_s(:db), developer.attributes_before_type_cast["created_at"].to_s(:db) else assert_equal developer.created_at.to_s(:db), developer.attributes_before_type_cast["created_at"].to_s -- cgit v1.2.3 From 351331fb343cdf17baa078943898ded6caff9d65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Guillermo=20=C3=81lvarez?= Date: Thu, 3 Feb 2011 00:26:39 +0100 Subject: Make serialized columns with explicit object_type return a new instance of the object instead of nil --- activerecord/test/cases/base_test.rb | 19 +++++++++++++++++++ activerecord/test/cases/coders/yaml_column_test.rb | 5 +++-- 2 files changed, 22 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 5cbc52732b..a255c07957 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -1002,6 +1002,25 @@ class BasicsTest < ActiveRecord::TestCase Topic.serialize(:content) end + def test_serialized_default_class + Topic.serialize(:content, Hash) + topic = Topic.new + assert_equal Hash, topic.content.class + assert_equal Hash, topic.read_attribute(:content).class + topic.content["beer"] = "MadridRb" + assert topic.save + topic.reload + assert_equal Hash, topic.content.class + assert_equal "MadridRb", topic.content["beer"] + ensure + Topic.serialize(:content) + end + + def test_serialized_no_default_class_for_object + topic = Topic.new + assert_nil topic.content + end + def test_serialized_boolean_value_true Topic.serialize(:content) topic = Topic.new(:content => true) diff --git a/activerecord/test/cases/coders/yaml_column_test.rb b/activerecord/test/cases/coders/yaml_column_test.rb index f85f11b57f..c7dcc21809 100644 --- a/activerecord/test/cases/coders/yaml_column_test.rb +++ b/activerecord/test/cases/coders/yaml_column_test.rb @@ -1,3 +1,4 @@ + require "cases/helper" module ActiveRecord @@ -20,9 +21,9 @@ module ActiveRecord assert_nil coder.load "--- " end - def test_nil_is_ok_with_different_class + def test_returns_new_with_different_class coder = YAMLColumn.new SerializationTypeMismatch - assert_nil coder.load "--- " + assert_equal SerializationTypeMismatch, coder.load("--- ").class end def test_returns_string_unless_starts_with_dash -- cgit v1.2.3 From d65e3b481e72e8c76818a94353e9ac315c7c0272 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Thu, 3 Feb 2011 11:50:43 -0800 Subject: ARel only requires the connection from the AR class. Simply return the AR class rather than jump through hoops and store ivars --- activerecord/test/cases/multiple_db_test.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/multiple_db_test.rb b/activerecord/test/cases/multiple_db_test.rb index bd51388e05..3daf81c828 100644 --- a/activerecord/test/cases/multiple_db_test.rb +++ b/activerecord/test/cases/multiple_db_test.rb @@ -84,8 +84,8 @@ class MultipleDbTest < ActiveRecord::TestCase assert_equal "Ruby Developer", Entrant.find(1).name end - def test_arel_table_engines - assert_not_equal Entrant.arel_engine, Course.arel_engine - assert_equal Entrant.arel_engine, Bird.arel_engine + def test_connections + assert_not_equal Entrant.connection, Course.connection + assert_equal Entrant.connection, Bird.connection end end -- cgit v1.2.3 From 95d5d9b6c48c08f1fba0c77ecbc97b62b2603824 Mon Sep 17 00:00:00 2001 From: Ken Collins Date: Thu, 3 Feb 2011 15:07:03 -0500 Subject: The type_cast_calculated_value method will trust DB types before casting to a BigDecimal. [#6365 state:committed] Signed-off-by: Santiago Pastorino --- activerecord/test/cases/calculations_test.rb | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index 644c9cb528..3121f1615d 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -28,6 +28,12 @@ class CalculationsTest < ActiveRecord::TestCase assert_equal 3.5, value end + def test_should_return_integer_average_if_db_returns_such + Account.connection.stubs :select_value => 3 + value = Account.average(:id) + assert_equal 3, value + end + def test_should_return_nil_as_average assert_nil NumericData.average(:bank_balance) end -- cgit v1.2.3 From 23a3ba426067d3d38259ef4e1d234cbb82c8aea2 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Thu, 3 Feb 2011 14:04:21 -0800 Subject: Revert "ARel only requires the connection from the AR class. Simply return the AR class rather than jump through hoops and store ivars" This reverts commit d65e3b481e72e8c76818a94353e9ac315c7c0272. --- activerecord/test/cases/multiple_db_test.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/multiple_db_test.rb b/activerecord/test/cases/multiple_db_test.rb index 3daf81c828..bd51388e05 100644 --- a/activerecord/test/cases/multiple_db_test.rb +++ b/activerecord/test/cases/multiple_db_test.rb @@ -84,8 +84,8 @@ class MultipleDbTest < ActiveRecord::TestCase assert_equal "Ruby Developer", Entrant.find(1).name end - def test_connections - assert_not_equal Entrant.connection, Course.connection - assert_equal Entrant.connection, Bird.connection + def test_arel_table_engines + assert_not_equal Entrant.arel_engine, Course.arel_engine + assert_equal Entrant.arel_engine, Bird.arel_engine end end -- cgit v1.2.3 From 7423a71fc02c0ca3bf37b94e16a1322c0caaa6fd Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Thu, 3 Feb 2011 15:35:34 -0800 Subject: allow AR caches to be cleared, clear them on class reloading --- activerecord/test/cases/base_test.rb | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index a255c07957..68adeff882 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -1553,6 +1553,14 @@ class BasicsTest < ActiveRecord::TestCase end end + def test_clear_cache! + # preheat cache + c1 = Post.columns + ActiveRecord::Base.clear_cache! + c2 = Post.columns + assert_not_equal c1, c2 + end + def test_default_scope_is_reset Object.const_set :UnloadablePost, Class.new(ActiveRecord::Base) UnloadablePost.table_name = 'posts' -- cgit v1.2.3 From df077604865b12b119be0259575675f45b958524 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 4 Feb 2011 13:34:41 -0800 Subject: introduce a fake AR adapter for mocking database return values --- .../connection_adapters/fake_adapter.rb | 36 ++++++++++++++++++++++ activerecord/test/models/contact.rb | 12 +++++--- 2 files changed, 43 insertions(+), 5 deletions(-) create mode 100644 activerecord/test/active_record/connection_adapters/fake_adapter.rb (limited to 'activerecord/test') diff --git a/activerecord/test/active_record/connection_adapters/fake_adapter.rb b/activerecord/test/active_record/connection_adapters/fake_adapter.rb new file mode 100644 index 0000000000..1c2942170e --- /dev/null +++ b/activerecord/test/active_record/connection_adapters/fake_adapter.rb @@ -0,0 +1,36 @@ +module ActiveRecord + class Base + def self.fake_connection(config) + ConnectionAdapters::FakeAdapter.new nil, logger + end + end + + module ConnectionAdapters + class FakeAdapter < AbstractAdapter + attr_accessor :tables, :primary_keys + + def initialize(connection, logger) + super + @tables = [] + @primary_keys = {} + @columns = Hash.new { |h,k| h[k] = [] } + end + + def primary_key(table) + @primary_keys[table] + end + + def merge_column(table_name, name, sql_type = nil, options = {}) + @columns[table_name] << ActiveRecord::ConnectionAdapters::Column.new( + name.to_s, + options[:default], + sql_type.to_s, + options[:null]) + end + + def columns(table_name, message) + @columns[table_name] + end + end + end +end diff --git a/activerecord/test/models/contact.rb b/activerecord/test/models/contact.rb index 5bbe7ebb12..e081eee661 100644 --- a/activerecord/test/models/contact.rb +++ b/activerecord/test/models/contact.rb @@ -1,12 +1,14 @@ class Contact < ActiveRecord::Base - def self.columns - @columns - end + establish_connection(:adapter => 'fake') + + connection.tables = ['contacts'] + connection.primary_keys = { + 'contacts' => 'id' + } # mock out self.columns so no pesky db is needed for these tests def self.column(name, sql_type = nil, options = {}) - @columns ||= [] - @columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, options[:default], sql_type.to_s, options[:null]) + connection.merge_column('contacts', name, sql_type, options) end column :name, :string -- cgit v1.2.3 From 909588d964bf27f20142a0b4d57890114a8d4a7a Mon Sep 17 00:00:00 2001 From: Edward Faulkner Date: Fri, 4 Feb 2011 15:34:44 -0500 Subject: Fixing ordering of HABTM association deletion [#6191 state:resolved] Signed-off-by: Santiago Pastorino --- .../has_and_belongs_to_many_associations_test.rb | 2 +- activerecord/test/cases/habtm_destroy_order_test.rb | 17 +++++++++++++++++ activerecord/test/models/lesson.rb | 11 +++++++++++ activerecord/test/models/student.rb | 3 +++ activerecord/test/schema/schema.rb | 13 +++++++++++++ 5 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 activerecord/test/cases/habtm_destroy_order_test.rb create mode 100644 activerecord/test/models/lesson.rb create mode 100644 activerecord/test/models/student.rb (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index 30730c7094..55b611ca92 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -365,7 +365,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase def test_removing_associations_on_destroy david = DeveloperWithBeforeDestroyRaise.find(1) assert !david.projects.empty? - assert_raise(RuntimeError) { david.destroy } + david.destroy assert david.projects.empty? assert DeveloperWithBeforeDestroyRaise.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = 1").empty? end diff --git a/activerecord/test/cases/habtm_destroy_order_test.rb b/activerecord/test/cases/habtm_destroy_order_test.rb new file mode 100644 index 0000000000..15598392e2 --- /dev/null +++ b/activerecord/test/cases/habtm_destroy_order_test.rb @@ -0,0 +1,17 @@ +require "cases/helper" +require "models/lesson" +require "models/student" + +class HabtmDestroyOrderTest < ActiveRecord::TestCase + test "may not delete a lesson with students" do + sicp = Lesson.new(:name => "SICP") + ben = Student.new(:name => "Ben Bitdiddle") + sicp.students << ben + sicp.save! + assert_raises LessonError do + assert_no_difference('Lesson.count') do + sicp.destroy + end + end + end +end diff --git a/activerecord/test/models/lesson.rb b/activerecord/test/models/lesson.rb new file mode 100644 index 0000000000..4c88153068 --- /dev/null +++ b/activerecord/test/models/lesson.rb @@ -0,0 +1,11 @@ +class LessonError < Exception +end + +class Lesson < ActiveRecord::Base + has_and_belongs_to_many :students + before_destroy :ensure_no_students + + def ensure_no_students + raise LessonError unless students.empty? + end +end diff --git a/activerecord/test/models/student.rb b/activerecord/test/models/student.rb new file mode 100644 index 0000000000..f459f2a9a3 --- /dev/null +++ b/activerecord/test/models/student.rb @@ -0,0 +1,3 @@ +class Student < ActiveRecord::Base + has_and_belongs_to_many :lessons +end diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 5f9bb7ee41..326c336317 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -279,6 +279,15 @@ ActiveRecord::Schema.define do t.integer :version, :null => false, :default => 0 end + create_table :lessons, :force => true do |t| + t.string :name + end + + create_table :lessons_students, :id => false, :force => true do |t| + t.references :lesson + t.references :student + end + create_table :line_items, :force => true do |t| t.integer :invoice_id t.integer :amount @@ -509,6 +518,10 @@ ActiveRecord::Schema.define do t.string :sponsorable_type end + create_table :students, :force => true do |t| + t.string :name + end + create_table :subscribers, :force => true, :id => false do |t| t.string :nick, :null => false t.string :name -- cgit v1.2.3 From 5f3cf4244de4fd62049d08df4e6bf63c945ab90e Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 4 Feb 2011 10:19:02 -0800 Subject: connection pool can cache column, table, and primary key information --- activerecord/test/cases/connection_pool_test.rb | 35 +++++++++++++++++++++++++ 1 file changed, 35 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb index 2e18117895..27fc3cab49 100644 --- a/activerecord/test/cases/connection_pool_test.rb +++ b/activerecord/test/cases/connection_pool_test.rb @@ -3,6 +3,41 @@ require "cases/helper" module ActiveRecord module ConnectionAdapters class ConnectionPoolTest < ActiveRecord::TestCase + def setup + # Keep a duplicate pool so we do not bother others + @pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec + end + + def test_pool_caches_columns + columns = @pool.columns['posts'] + assert_equal columns, @pool.columns['posts'] + end + + def test_pool_caches_columns_hash + columns_hash = @pool.columns_hash['posts'] + assert_equal columns_hash, @pool.columns_hash['posts'] + end + + def test_clearing_cache + @pool.columns['posts'] + @pool.columns_hash['posts'] + @pool.primary_keys['posts'] + + @pool.clear_cache! + + assert_equal 0, @pool.columns.size + assert_equal 0, @pool.columns_hash.size + assert_equal 0, @pool.primary_keys.size + end + + def test_primary_key + assert_equal 'id', @pool.primary_keys['posts'] + end + + def test_primary_key_for_non_existent_table + assert_equal 'id', @pool.primary_keys['omgponies'] + end + def test_clear_stale_cached_connections! pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec -- cgit v1.2.3 From 0cd42864e3dcba520980f952be9a09c01beddb03 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 4 Feb 2011 12:15:30 -0800 Subject: making sure primary key is set on the columns --- activerecord/test/cases/connection_pool_test.rb | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb index 27fc3cab49..0727e86705 100644 --- a/activerecord/test/cases/connection_pool_test.rb +++ b/activerecord/test/cases/connection_pool_test.rb @@ -38,6 +38,15 @@ module ActiveRecord assert_equal 'id', @pool.primary_keys['omgponies'] end + def test_primary_key_is_set_on_columns + posts_columns = @pool.columns_hash['posts'] + assert posts_columns['id'].primary + + (posts_columns.keys - ['id']).each do |key| + assert !posts_columns[key].primary + end + end + def test_clear_stale_cached_connections! pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec -- cgit v1.2.3 From c94651f8c822f7c0778c03eb36bee5ca19f35911 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 4 Feb 2011 14:52:05 -0800 Subject: almost fisted --- .../cases/associations/has_and_belongs_to_many_associations_test.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index 55b611ca92..49cfac2170 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -757,10 +757,10 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase david = Developer.find(1) # clear cache possibly created by other tests david.projects.reset_column_information - assert_queries(0) { david.projects.columns; david.projects.columns } + assert_queries(1) { david.projects.columns; david.projects.columns } # and again to verify that reset_column_information clears the cache correctly david.projects.reset_column_information - assert_queries(0) { david.projects.columns; david.projects.columns } + assert_queries(1) { david.projects.columns; david.projects.columns } end def test_attributes_are_being_set_when_initialized_from_habm_association_with_where_clause -- cgit v1.2.3 From acccb72cb12ab55bb01c3dce32f54f4a59ebec6c Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 4 Feb 2011 15:54:32 -0800 Subject: column cache now lives on the connection pool --- .../has_and_belongs_to_many_associations_test.rb | 4 ++-- activerecord/test/cases/connection_pool_test.rb | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index 49cfac2170..55b611ca92 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -757,10 +757,10 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase david = Developer.find(1) # clear cache possibly created by other tests david.projects.reset_column_information - assert_queries(1) { david.projects.columns; david.projects.columns } + assert_queries(0) { david.projects.columns; david.projects.columns } # and again to verify that reset_column_information clears the cache correctly david.projects.reset_column_information - assert_queries(1) { david.projects.columns; david.projects.columns } + assert_queries(0) { david.projects.columns; david.projects.columns } end def test_attributes_are_being_set_when_initialized_from_habm_association_with_where_clause diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb index 0727e86705..55ac1bc406 100644 --- a/activerecord/test/cases/connection_pool_test.rb +++ b/activerecord/test/cases/connection_pool_test.rb @@ -99,6 +99,26 @@ module ActiveRecord end.join() end + + def test_automatic_reconnect= + pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec + assert pool.automatic_reconnect + assert pool.connection + + pool.disconnect! + assert pool.connection + + pool.disconnect! + pool.automatic_reconnect = false + + assert_raises(ConnectionNotEstablished) do + pool.connection + end + + assert_raises(ConnectionNotEstablished) do + pool.with_connection + end + end end end end -- cgit v1.2.3 From 59f7780a3454a14054d1d33d9b6e31192ab2e58b Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 4 Feb 2011 18:08:31 -0800 Subject: adjust query counts to be consistent across databases, make sure database log the same things --- .../associations/has_and_belongs_to_many_associations_test.rb | 9 ++++++--- activerecord/test/cases/helper.rb | 2 +- activerecord/test/cases/migration_test.rb | 5 ++++- 3 files changed, 11 insertions(+), 5 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index 55b611ca92..126b767d06 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -757,10 +757,13 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase david = Developer.find(1) # clear cache possibly created by other tests david.projects.reset_column_information - assert_queries(0) { david.projects.columns; david.projects.columns } - # and again to verify that reset_column_information clears the cache correctly + + # One query for columns, one for primary key + assert_queries(2) { david.projects.columns; david.projects.columns } + + ## and again to verify that reset_column_information clears the cache correctly david.projects.reset_column_information - assert_queries(0) { david.projects.columns; david.projects.columns } + assert_queries(2) { david.projects.columns; david.projects.columns } end def test_attributes_are_being_set_when_initialized_from_habm_association_with_where_clause diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 2cc993b6ed..97bb631d2d 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -50,7 +50,7 @@ ensure end ActiveRecord::Base.connection.class.class_eval do - IGNORED_SQL = [/^PRAGMA/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/, /SHOW FIELDS/] + IGNORED_SQL = [/^PRAGMA (?!(table_info))/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/] # FIXME: this needs to be refactored so specific database can add their own # ignored SQL. This ignored SQL is for Oracle. diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index 6f0f73e3bd..9d7c49768b 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -2022,7 +2022,10 @@ if ActiveRecord::Base.connection.supports_migrations? assert ! column(:name).default assert_equal :date, column(:birthdate).type - assert_queries(1) do + # One query for columns (delete_me table) + # One query for primary key (delete_me table) + # One query to do the bulk change + assert_queries(3) do with_bulk_change_table do |t| t.change :name, :string, :default => 'NONAME' t.change :birthdate, :datetime -- cgit v1.2.3 From 40aefb93018277ee7cafc5529b16d7b6df8aa4dd Mon Sep 17 00:00:00 2001 From: Akira Matsuda Date: Mon, 7 Feb 2011 08:29:06 +0900 Subject: avoid nil.dup Signed-off-by: Santiago Pastorino --- activerecord/test/cases/attribute_methods_test.rb | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb index 7e3e204626..c343dd7918 100644 --- a/activerecord/test/cases/attribute_methods_test.rb +++ b/activerecord/test/cases/attribute_methods_test.rb @@ -460,6 +460,14 @@ class AttributeMethodsTest < ActiveRecord::TestCase end end + def test_write_nil_to_time_attributes + in_time_zone "Pacific Time (US & Canada)" do + record = @target.new + record.written_on = nil + assert_nil record.written_on + end + end + def test_time_attributes_are_retrieved_in_current_time_zone in_time_zone "Pacific Time (US & Canada)" do utc_time = Time.utc(2008, 1, 1) -- cgit v1.2.3 From 65e08cfb4fdf30a38162477dc8b644c6fad74d93 Mon Sep 17 00:00:00 2001 From: Akira Matsuda Date: Mon, 7 Feb 2011 19:51:52 +0900 Subject: do not to_s where you are testing that a string value is stored for the before_type_cast Signed-off-by: Santiago Pastorino --- activerecord/test/cases/attribute_methods_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb index c343dd7918..88eaea62e8 100644 --- a/activerecord/test/cases/attribute_methods_test.rb +++ b/activerecord/test/cases/attribute_methods_test.rb @@ -131,7 +131,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase assert_equal developer.created_at, nil developer.created_at = "2010-03-21 21:23:32" - assert_equal developer.created_at_before_type_cast.to_s, "2010-03-21 21:23:32" + assert_equal developer.created_at_before_type_cast, "2010-03-21 21:23:32" assert_equal developer.created_at, Time.parse("2010-03-21 21:23:32") end -- cgit v1.2.3 From 0de661d6c74172a9fedcced6a4e99d007df953ef Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 7 Feb 2011 09:25:57 -0800 Subject: the connection pool caches table_exists? calls --- activerecord/test/cases/associations/eager_test.rb | 2 ++ 1 file changed, 2 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index e11f1009dc..3074648d59 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -851,6 +851,8 @@ class EagerAssociationTest < ActiveRecord::TestCase end def test_eager_loading_with_conditions_on_join_model_preloads + Author.columns + authors = assert_queries(2) do Author.find(:all, :include => :author_address, :joins => :comments, :conditions => "posts.title like 'Welcome%'") end -- cgit v1.2.3 From 1193709cd693099488353c20f2c7fadcf9cd6d05 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 7 Feb 2011 14:35:00 -0800 Subject: removing some freedom patches. use notification system to count sql queries --- activerecord/test/cases/helper.rb | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 97bb631d2d..499b30b4e8 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -49,28 +49,29 @@ ensure ActiveRecord::Base.default_timezone = old_zone end -ActiveRecord::Base.connection.class.class_eval do - IGNORED_SQL = [/^PRAGMA (?!(table_info))/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/] +module ActiveRecord + class SQLCounter + IGNORED_SQL = [/^PRAGMA (?!(table_info))/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/] - # FIXME: this needs to be refactored so specific database can add their own - # ignored SQL. This ignored SQL is for Oracle. - IGNORED_SQL.concat [/^select .*nextval/i, /^SAVEPOINT/, /^ROLLBACK TO/, /^\s*select .* from ((all|user)_tab_columns|(all|user)_triggers|(all|user)_constraints)/im] + # FIXME: this needs to be refactored so specific database can add their own + # ignored SQL. This ignored SQL is for Oracle. + IGNORED_SQL.concat [/^select .*nextval/i, /^SAVEPOINT/, /^ROLLBACK TO/, /^\s*select .* from ((all|user)_tab_columns|(all|user)_triggers|(all|user)_constraints)/im] - def execute_with_query_record(sql, name = nil, &block) - $queries_executed ||= [] - $queries_executed << sql unless IGNORED_SQL.any? { |r| sql =~ r } - execute_without_query_record(sql, name, &block) - end + def initialize + $queries_executed = [] + end - alias_method_chain :execute, :query_record + def call(name, start, finish, message_id, values) + sql = values[:sql] - def exec_query_with_query_record(sql, name = nil, binds = [], &block) - $queries_executed ||= [] - $queries_executed << sql unless IGNORED_SQL.any? { |r| sql =~ r } - exec_query_without_query_record(sql, name, binds, &block) + # FIXME: this seems bad. we should probably have a better way to indicate + # the query was cached + unless 'CACHE' == values[:name] + $queries_executed << sql unless IGNORED_SQL.any? { |r| sql =~ r } + end + end end - - alias_method_chain :exec_query, :query_record + ActiveSupport::Notifications.subscribe('sql.active_record', SQLCounter.new) end ActiveRecord::Base.connection.class.class_eval { -- cgit v1.2.3 From 30bba95a048af7f64724fe2450ad14967581a456 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 7 Feb 2011 15:12:21 -0800 Subject: update ignored SQL for oracle --- activerecord/test/cases/helper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 499b30b4e8..8c001096cc 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -55,7 +55,7 @@ module ActiveRecord # FIXME: this needs to be refactored so specific database can add their own # ignored SQL. This ignored SQL is for Oracle. - IGNORED_SQL.concat [/^select .*nextval/i, /^SAVEPOINT/, /^ROLLBACK TO/, /^\s*select .* from ((all|user)_tab_columns|(all|user)_triggers|(all|user)_constraints)/im] + IGNORED_SQL.concat [/^select .*nextval/i, /^SAVEPOINT/, /^ROLLBACK TO/, /^\s*select .* from all_triggers/im] def initialize $queries_executed = [] -- cgit v1.2.3 From 5f1ea2a26b6e29f235e132d565b53f12e0234c66 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 7 Feb 2011 15:28:49 -0800 Subject: we do not use this method, so delete --- activerecord/test/cases/helper.rb | 12 ------------ 1 file changed, 12 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 8c001096cc..1019ea1dda 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -74,18 +74,6 @@ module ActiveRecord ActiveSupport::Notifications.subscribe('sql.active_record', SQLCounter.new) end -ActiveRecord::Base.connection.class.class_eval { - attr_accessor :column_calls - - def columns_with_calls(*args) - @column_calls ||= 0 - @column_calls += 1 - columns_without_calls(*args) - end - - alias_method_chain :columns, :calls -} - unless ENV['FIXTURE_DEBUG'] module ActiveRecord::TestFixtures::ClassMethods def try_to_load_dependency_with_silence(*args) -- cgit v1.2.3 From d55406d2e991056b08f69eb68bcf9b17da807b6c Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sun, 30 Jan 2011 19:07:08 +0000 Subject: Make record.association.destroy(*records) on habtm and hm:t only delete records in the join table. This is to make the destroy method more consistent across the different types of associations. For more details see the CHANGELOG entry. --- .../has_and_belongs_to_many_associations_test.rb | 30 ++- .../has_many_through_associations_test.rb | 12 +- .../test/cases/autosave_association_test.rb | 241 +++++++++++++++------ 3 files changed, 199 insertions(+), 84 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index 126b767d06..5dd2c9861e 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -372,27 +372,34 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase def test_destroying david = Developer.find(1) - active_record = Project.find(1) + project = Project.find(1) david.projects.reload assert_equal 2, david.projects.size - assert_equal 3, active_record.developers.size + assert_equal 3, project.developers.size - assert_difference "Project.count", -1 do - david.projects.destroy(active_record) + assert_no_difference "Project.count" do + david.projects.destroy(project) end + join_records = Developer.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id} AND project_id = #{project.id}") + assert join_records.empty? + assert_equal 1, david.reload.projects.size assert_equal 1, david.projects(true).size end - def test_destroying_array + def test_destroying_many david = Developer.find(1) david.projects.reload + projects = Project.all - assert_difference "Project.count", -Project.count do - david.projects.destroy(Project.find(:all)) + assert_no_difference "Project.count" do + david.projects.destroy(*projects) end + join_records = Developer.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id}") + assert join_records.empty? + assert_equal 0, david.reload.projects.size assert_equal 0, david.projects(true).size end @@ -401,7 +408,14 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase david = Developer.find(1) david.projects.reload assert !david.projects.empty? - david.projects.destroy_all + + assert_no_difference "Project.count" do + david.projects.destroy_all + end + + join_records = Developer.connection.select_all("SELECT * FROM developers_projects WHERE developer_id = #{david.id}") + assert join_records.empty? + assert david.projects.empty? assert david.projects(true).empty? end diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 96f4597726..6830478107 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -128,8 +128,10 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase end def test_destroy_association - assert_difference ["Person.count", "Reader.count"], -1 do - posts(:welcome).people.destroy(people(:michael)) + assert_no_difference "Person.count" do + assert_difference "Reader.count", -1 do + posts(:welcome).people.destroy(people(:michael)) + end end assert posts(:welcome).reload.people.empty? @@ -137,8 +139,10 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase end def test_destroy_all - assert_difference ["Person.count", "Reader.count"], -1 do - posts(:welcome).people.destroy_all + assert_no_difference "Person.count" do + assert_difference "Reader.count", -1 do + posts(:welcome).people.destroy_all + end end assert posts(:welcome).reload.people.empty? diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index 11c0c5b0ef..c2f2609c9e 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -689,110 +689,207 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase assert_equal 'NewName', @parrot.reload.name end - # has_many & has_and_belongs_to - %w{ parrots birds }.each do |association_name| - define_method("test_should_destroy_#{association_name}_as_part_of_the_save_transaction_if_they_were_marked_for_destroyal") do - 2.times { |i| @pirate.send(association_name).create!(:name => "#{association_name}_#{i}") } + def test_should_destroy_has_many_as_part_of_the_save_transaction_if_they_were_marked_for_destruction + 2.times { |i| @pirate.birds.create!(:name => "birds_#{i}") } - assert !@pirate.send(association_name).any? { |child| child.marked_for_destruction? } + assert !@pirate.birds.any? { |child| child.marked_for_destruction? } - @pirate.send(association_name).each { |child| child.mark_for_destruction } - klass = @pirate.send(association_name).first.class - ids = @pirate.send(association_name).map(&:id) + @pirate.birds.each { |child| child.mark_for_destruction } + klass = @pirate.birds.first.class + ids = @pirate.birds.map(&:id) - assert @pirate.send(association_name).all? { |child| child.marked_for_destruction? } - ids.each { |id| assert klass.find_by_id(id) } + assert @pirate.birds.all? { |child| child.marked_for_destruction? } + ids.each { |id| assert klass.find_by_id(id) } - @pirate.save - assert @pirate.reload.send(association_name).empty? - ids.each { |id| assert_nil klass.find_by_id(id) } + @pirate.save + assert @pirate.reload.birds.empty? + ids.each { |id| assert_nil klass.find_by_id(id) } + end + + def test_should_skip_validation_on_has_many_if_marked_for_destruction + 2.times { |i| @pirate.birds.create!(:name => "birds_#{i}") } + + @pirate.birds.each { |bird| bird.name = '' } + assert !@pirate.valid? + + @pirate.birds.each do |bird| + bird.mark_for_destruction + bird.expects(:valid?).never end + assert_difference("Bird.count", -2) { @pirate.save! } + end + + def test_should_skip_validation_on_has_many_if_destroyed + @pirate.birds.create!(:name => "birds_1") - define_method("test_should_skip_validation_on_the_#{association_name}_association_if_marked_for_destruction") do - 2.times { |i| @pirate.send(association_name).create!(:name => "#{association_name}_#{i}") } - children = @pirate.send(association_name) + @pirate.birds.each { |bird| bird.name = '' } + assert !@pirate.valid? + + @pirate.birds.each { |bird| bird.destroy } + assert @pirate.valid? + end - children.each { |child| child.name = '' } - assert !@pirate.valid? + def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_has_many + @pirate.birds.create!(:name => "birds_1") + + @pirate.birds.each { |bird| bird.mark_for_destruction } + assert @pirate.save + + @pirate.birds.each { |bird| bird.expects(:destroy).never } + assert @pirate.save + end - children.each do |child| - child.mark_for_destruction - child.expects(:valid?).never + def test_should_rollback_destructions_if_an_exception_occurred_while_saving_has_many + 2.times { |i| @pirate.birds.create!(:name => "birds_#{i}") } + before = @pirate.birds.map { |c| c.mark_for_destruction ; c } + + # Stub the destroy method of the the second child to raise an exception + class << before.last + def destroy(*args) + super + raise 'Oh noes!' end - assert_difference("#{association_name.classify}.count", -2) { @pirate.save! } end - define_method("test_should_skip_validation_on_the_#{association_name}_association_if_destroyed") do - @pirate.send(association_name).create!(:name => "#{association_name}_1") - children = @pirate.send(association_name) + assert_raise(RuntimeError) { assert !@pirate.save } + assert_equal before, @pirate.reload.birds + end + + # Add and remove callbacks tests for association collections. + %w{ method proc }.each do |callback_type| + define_method("test_should_run_add_callback_#{callback_type}s_for_has_many") do + association_name_with_callbacks = "birds_with_#{callback_type}_callbacks" + + pirate = Pirate.new(:catchphrase => "Arr") + pirate.send(association_name_with_callbacks).build(:name => "Crowe the One-Eyed") - children.each { |child| child.name = '' } - assert !@pirate.valid? + expected = [ + "before_adding_#{callback_type}_bird_", + "after_adding_#{callback_type}_bird_" + ] - children.each { |child| child.destroy } - assert @pirate.valid? + assert_equal expected, pirate.ship_log end - define_method("test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_#{association_name}") do - @pirate.send(association_name).create!(:name => "#{association_name}_1") - children = @pirate.send(association_name) + define_method("test_should_run_remove_callback_#{callback_type}s_for_has_many") do + association_name_with_callbacks = "birds_with_#{callback_type}_callbacks" - children.each { |child| child.mark_for_destruction } - assert @pirate.save - children.each { |child| child.expects(:destroy).never } - assert @pirate.save + @pirate.send(association_name_with_callbacks).create!(:name => "Crowe the One-Eyed") + @pirate.send(association_name_with_callbacks).each { |c| c.mark_for_destruction } + child_id = @pirate.send(association_name_with_callbacks).first.id + + @pirate.ship_log.clear + @pirate.save + + expected = [ + "before_removing_#{callback_type}_bird_#{child_id}", + "after_removing_#{callback_type}_bird_#{child_id}" + ] + + assert_equal expected, @pirate.ship_log end + end - define_method("test_should_rollback_destructions_if_an_exception_occurred_while_saving_#{association_name}") do - 2.times { |i| @pirate.send(association_name).create!(:name => "#{association_name}_#{i}") } - before = @pirate.send(association_name).map { |c| c.mark_for_destruction ; c } + def test_should_destroy_habtm_as_part_of_the_save_transaction_if_they_were_marked_for_destruction + 2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") } - # Stub the destroy method of the the second child to raise an exception - class << before.last - def destroy(*args) - super - raise 'Oh noes!' - end - end + assert !@pirate.parrots.any? { |parrot| parrot.marked_for_destruction? } + @pirate.parrots.each { |parrot| parrot.mark_for_destruction } - assert_raise(RuntimeError) { assert !@pirate.save } - assert_equal before, @pirate.reload.send(association_name) + assert_no_difference "Parrot.count" do + @pirate.save end - # Add and remove callbacks tests for association collections. - %w{ method proc }.each do |callback_type| - define_method("test_should_run_add_callback_#{callback_type}s_for_#{association_name}") do - association_name_with_callbacks = "#{association_name}_with_#{callback_type}_callbacks" + assert @pirate.reload.parrots.empty? - pirate = Pirate.new(:catchphrase => "Arr") - pirate.send(association_name_with_callbacks).build(:name => "Crowe the One-Eyed") + join_records = Pirate.connection.select_all("SELECT * FROM parrots_pirates WHERE pirate_id = #{@pirate.id}") + assert join_records.empty? + end - expected = [ - "before_adding_#{callback_type}_#{association_name.singularize}_", - "after_adding_#{callback_type}_#{association_name.singularize}_" - ] + def test_should_skip_validation_on_habtm_if_marked_for_destruction + 2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") } - assert_equal expected, pirate.ship_log - end + @pirate.parrots.each { |parrot| parrot.name = '' } + assert !@pirate.valid? + + @pirate.parrots.each do |parrot| + parrot.mark_for_destruction + parrot.expects(:valid?).never + end - define_method("test_should_run_remove_callback_#{callback_type}s_for_#{association_name}") do - association_name_with_callbacks = "#{association_name}_with_#{callback_type}_callbacks" + @pirate.save! + assert @pirate.reload.parrots.empty? + end + + def test_should_skip_validation_on_habtm_if_destroyed + @pirate.parrots.create!(:name => "parrots_1") - @pirate.send(association_name_with_callbacks).create!(:name => "Crowe the One-Eyed") - @pirate.send(association_name_with_callbacks).each { |c| c.mark_for_destruction } - child_id = @pirate.send(association_name_with_callbacks).first.id + @pirate.parrots.each { |parrot| parrot.name = '' } + assert !@pirate.valid? - @pirate.ship_log.clear - @pirate.save + @pirate.parrots.each { |parrot| parrot.destroy } + assert @pirate.valid? + end + + def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_habtm + @pirate.parrots.create!(:name => "parrots_1") + + @pirate.parrots.each { |parrot| parrot.mark_for_destruction } + assert @pirate.save + + assert_queries(1) do + assert @pirate.save + end + end - expected = [ - "before_removing_#{callback_type}_#{association_name.singularize}_#{child_id}", - "after_removing_#{callback_type}_#{association_name.singularize}_#{child_id}" - ] + def test_should_rollback_destructions_if_an_exception_occurred_while_saving_habtm + 2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") } + before = @pirate.parrots.map { |c| c.mark_for_destruction ; c } - assert_equal expected, @pirate.ship_log + class << @pirate.parrots + def destroy(*args) + super + raise 'Oh noes!' end end + + assert_raise(RuntimeError) { assert !@pirate.save } + assert_equal before, @pirate.reload.parrots + end + + # Add and remove callbacks tests for association collections. + %w{ method proc }.each do |callback_type| + define_method("test_should_run_add_callback_#{callback_type}s_for_habtm") do + association_name_with_callbacks = "parrots_with_#{callback_type}_callbacks" + + pirate = Pirate.new(:catchphrase => "Arr") + pirate.send(association_name_with_callbacks).build(:name => "Crowe the One-Eyed") + + expected = [ + "before_adding_#{callback_type}_parrot_", + "after_adding_#{callback_type}_parrot_" + ] + + assert_equal expected, pirate.ship_log + end + + define_method("test_should_run_remove_callback_#{callback_type}s_for_habtm") do + association_name_with_callbacks = "parrots_with_#{callback_type}_callbacks" + + @pirate.send(association_name_with_callbacks).create!(:name => "Crowe the One-Eyed") + @pirate.send(association_name_with_callbacks).each { |c| c.mark_for_destruction } + child_id = @pirate.send(association_name_with_callbacks).first.id + + @pirate.ship_log.clear + @pirate.save + + expected = [ + "before_removing_#{callback_type}_parrot_#{child_id}", + "after_removing_#{callback_type}_parrot_#{child_id}" + ] + + assert_equal expected, @pirate.ship_log + end end end -- cgit v1.2.3 From 05bcb8cecc8573f28ad080839233b4bb9ace07be Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Tue, 1 Feb 2011 22:56:04 +0000 Subject: Support the :dependent option on has_many :through associations. For historical and practical reasons, :delete_all is the default deletion strategy employed by association.delete(*records), despite the fact that the default strategy is :nullify for regular has_many. Also, this only works at all if the source reflection is a belongs_to. For other situations, you should directly modify the through association. --- .../has_many_through_associations_test.rb | 100 +++++++++++++++++++++ activerecord/test/models/person.rb | 27 +++++- activerecord/test/models/reference.rb | 12 +++ activerecord/test/schema/schema.rb | 1 + 4 files changed, 139 insertions(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 6830478107..2aaf5750ba 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -155,6 +155,106 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase end end + def test_delete_through_belongs_to_with_dependent_nullify + Reference.make_comments = true + + person = people(:michael) + job = jobs(:magician) + reference = Reference.where(:job_id => job.id, :person_id => person.id).first + + assert_no_difference ['Job.count', 'Reference.count'] do + assert_difference 'person.jobs.count', -1 do + person.jobs_with_dependent_nullify.delete(job) + end + end + + assert_equal nil, reference.reload.job_id + ensure + Reference.make_comments = false + end + + def test_delete_through_belongs_to_with_dependent_delete_all + Reference.make_comments = true + + person = people(:michael) + job = jobs(:magician) + + # Make sure we're not deleting everything + assert person.jobs.count >= 2 + + assert_no_difference 'Job.count' do + assert_difference ['person.jobs.count', 'Reference.count'], -1 do + person.jobs_with_dependent_delete_all.delete(job) + end + end + + # Check that the destroy callback on Reference did not run + assert_equal nil, person.reload.comments + ensure + Reference.make_comments = false + end + + def test_delete_through_belongs_to_with_dependent_destroy + Reference.make_comments = true + + person = people(:michael) + job = jobs(:magician) + + # Make sure we're not deleting everything + assert person.jobs.count >= 2 + + assert_no_difference 'Job.count' do + assert_difference ['person.jobs.count', 'Reference.count'], -1 do + person.jobs_with_dependent_destroy.delete(job) + end + end + + # Check that the destroy callback on Reference ran + assert_equal "Reference destroyed", person.reload.comments + ensure + Reference.make_comments = false + end + + def test_belongs_to_with_dependent_destroy + person = PersonWithDependentDestroyJobs.find(1) + + # Create a reference which is not linked to a job. This should not be destroyed. + person.references.create! + + assert_no_difference 'Job.count' do + assert_difference 'Reference.count', -person.jobs.count do + person.destroy + end + end + end + + def test_belongs_to_with_dependent_delete_all + person = PersonWithDependentDeleteAllJobs.find(1) + + # Create a reference which is not linked to a job. This should not be destroyed. + person.references.create! + + assert_no_difference 'Job.count' do + assert_difference 'Reference.count', -person.jobs.count do + person.destroy + end + end + end + + def test_belongs_to_with_dependent_nullify + person = PersonWithDependentNullifyJobs.find(1) + + references = person.references.to_a + + assert_no_difference ['Reference.count', 'Job.count'] do + person.destroy + end + + references.each do |reference| + assert_equal nil, reference.reload.job_id + end + end + def test_replace_association assert_queries(4){posts(:welcome);people(:david);people(:michael); posts(:welcome).people(true)} diff --git a/activerecord/test/models/person.rb b/activerecord/test/models/person.rb index bee89de042..a18b9e44df 100644 --- a/activerecord/test/models/person.rb +++ b/activerecord/test/models/person.rb @@ -6,10 +6,14 @@ class Person < ActiveRecord::Base has_many :references has_many :bad_references has_many :fixed_bad_references, :conditions => { :favourite => true }, :class_name => 'BadReference' - has_many :jobs, :through => :references has_one :favourite_reference, :class_name => 'Reference', :conditions => ['favourite=?', true] has_many :posts_with_comments_sorted_by_comment_id, :through => :readers, :source => :post, :include => :comments, :order => 'comments.id' + has_many :jobs, :through => :references + has_many :jobs_with_dependent_destroy, :source => :job, :through => :references, :dependent => :destroy + has_many :jobs_with_dependent_delete_all, :source => :job, :through => :references, :dependent => :delete_all + has_many :jobs_with_dependent_nullify, :source => :job, :through => :references, :dependent => :nullify + belongs_to :primary_contact, :class_name => 'Person' has_many :agents, :class_name => 'Person', :foreign_key => 'primary_contact_id' has_many :agents_of_agents, :through => :agents, :source => :agents @@ -18,3 +22,24 @@ class Person < ActiveRecord::Base scope :males, :conditions => { :gender => 'M' } scope :females, :conditions => { :gender => 'F' } end + +class PersonWithDependentDestroyJobs < ActiveRecord::Base + self.table_name = 'people' + + has_many :references, :foreign_key => :person_id + has_many :jobs, :source => :job, :through => :references, :dependent => :destroy +end + +class PersonWithDependentDeleteAllJobs < ActiveRecord::Base + self.table_name = 'people' + + has_many :references, :foreign_key => :person_id + has_many :jobs, :source => :job, :through => :references, :dependent => :delete_all +end + +class PersonWithDependentNullifyJobs < ActiveRecord::Base + self.table_name = 'people' + + has_many :references, :foreign_key => :person_id + has_many :jobs, :source => :job, :through => :references, :dependent => :nullify +end diff --git a/activerecord/test/models/reference.rb b/activerecord/test/models/reference.rb index 4a17c936f5..06c4f79ef3 100644 --- a/activerecord/test/models/reference.rb +++ b/activerecord/test/models/reference.rb @@ -1,6 +1,18 @@ class Reference < ActiveRecord::Base belongs_to :person belongs_to :job + + class << self + attr_accessor :make_comments + end + + before_destroy :make_comments + + def make_comments + if self.class.make_comments + person.update_attributes :comments => "Reference destroyed" + end + end end class BadReference < ActiveRecord::Base diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 326c336317..09c7b7ba63 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -425,6 +425,7 @@ ActiveRecord::Schema.define do t.string :gender, :limit => 1 t.references :number1_fan t.integer :lock_version, :null => false, :default => 0 + t.string :comments end create_table :pets, :primary_key => :pet_id ,:force => true do |t| -- cgit v1.2.3 From 52f09eac5b3d297021ef726e04ec19f6011cb302 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sat, 5 Feb 2011 13:13:49 +0000 Subject: Correctly update counter caches on deletion for has_many :through [#2824 state:resolved]. Also fixed a bunch of other counter cache bugs in the process, as once I fixed this one others started appearing like nobody's business. --- .../associations/has_many_associations_test.rb | 22 +++++++---- .../has_many_through_associations_test.rb | 44 +++++++++++++++++++++- activerecord/test/fixtures/posts.yml | 2 + activerecord/test/models/post.rb | 5 +++ activerecord/test/schema/schema.rb | 4 ++ 5 files changed, 67 insertions(+), 10 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index e36124a055..23b777ac6d 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -630,7 +630,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal topic.replies.to_a.size, topic.replies_count end - def test_deleting_updates_counter_cache_without_dependent_destroy + def test_deleting_updates_counter_cache_without_dependent_option post = posts(:welcome) assert_difference "post.reload.taggings_count", -1 do @@ -640,16 +640,22 @@ class HasManyAssociationsTest < ActiveRecord::TestCase def test_deleting_updates_counter_cache_with_dependent_delete_all post = posts(:welcome) - - # Manually update the count as the tagging will have been added to the taggings association, - # rather than to the taggings_with_delete_all one (which is just a 'shadow' of the former) - post.update_attribute(:taggings_with_delete_all_count, post.taggings_with_delete_all.to_a.count) + post.update_attribute(:taggings_with_delete_all_count, post.taggings_count) assert_difference "post.reload.taggings_with_delete_all_count", -1 do post.taggings_with_delete_all.delete(post.taggings_with_delete_all.first) end end + def test_deleting_updates_counter_cache_with_dependent_destroy + post = posts(:welcome) + post.update_attribute(:taggings_with_destroy_count, post.taggings_count) + + assert_difference "post.reload.taggings_with_destroy_count", -1 do + post.taggings_with_destroy.delete(post.taggings_with_destroy.first) + end + end + def test_deleting_a_collection force_signal37_to_load_all_clients_of_firm companies(:first_firm).clients_of_firm.create("name" => "Another Client") @@ -701,9 +707,9 @@ class HasManyAssociationsTest < ActiveRecord::TestCase def test_clearing_updates_counter_cache topic = Topic.first - topic.replies.clear - topic.reload - assert_equal 0, topic.replies_count + assert_difference 'topic.reload.replies_count', -1 do + topic.replies.clear + end end def test_clearing_a_dependent_association_collection diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 2aaf5750ba..c58068ef75 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -25,8 +25,8 @@ require 'models/membership' require 'models/club' class HasManyThroughAssociationsTest < ActiveRecord::TestCase - fixtures :posts, :readers, :people, :comments, :authors, :categories, - :owners, :pets, :toys, :jobs, :references, :companies, :members, + fixtures :posts, :readers, :people, :comments, :authors, :categories, :taggings, :tags, + :owners, :pets, :toys, :jobs, :references, :companies, :members, :author_addresses, :subscribers, :books, :subscriptions, :developers, :categorizations # Dummies to force column loads so query counts are clean. @@ -255,6 +255,37 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase end end + def test_update_counter_caches_on_delete + post = posts(:welcome) + tag = post.tags.create!(:name => 'doomed') + + assert_difference ['post.reload.taggings_count', 'post.reload.tags_count'], -1 do + posts(:welcome).tags.delete(tag) + end + end + + def test_update_counter_caches_on_delete_with_dependent_destroy + post = posts(:welcome) + tag = post.tags.create!(:name => 'doomed') + post.update_attribute(:tags_with_destroy_count, post.tags.count) + + assert_difference ['post.reload.taggings_count', 'post.reload.tags_with_destroy_count'], -1 do + posts(:welcome).tags_with_destroy.delete(tag) + end + end + + def test_update_counter_caches_on_delete_with_dependent_nullify + post = posts(:welcome) + tag = post.tags.create!(:name => 'doomed') + post.update_attribute(:tags_with_nullify_count, post.tags.count) + + assert_no_difference 'post.reload.taggings_count' do + assert_difference 'post.reload.tags_with_nullify_count', -1 do + posts(:welcome).tags_with_nullify.delete(tag) + end + end + end + def test_replace_association assert_queries(4){posts(:welcome);people(:david);people(:michael); posts(:welcome).people(true)} @@ -671,4 +702,13 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase assert_equal true, club.reload.membership.favourite end + + def test_deleting_from_has_many_through_a_belongs_to_should_not_try_to_update_counter + post = posts(:welcome) + address = author_addresses(:david_address) + + assert post.author_addresses.include?(address) + post.author_addresses.delete(address) + assert post[:author_count].nil? + end end diff --git a/activerecord/test/fixtures/posts.yml b/activerecord/test/fixtures/posts.yml index f817493190..07069a064f 100644 --- a/activerecord/test/fixtures/posts.yml +++ b/activerecord/test/fixtures/posts.yml @@ -5,6 +5,7 @@ welcome: body: Such a lovely day comments_count: 2 taggings_count: 1 + tags_count: 1 type: Post thinking: @@ -14,6 +15,7 @@ thinking: body: Like I hopefully always am comments_count: 1 taggings_count: 1 + tags_count: 1 type: SpecialPost authorless: diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index 1c95d30d6b..fd8cd2244a 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -39,6 +39,7 @@ class Post < ActiveRecord::Base has_many :author_favorites, :through => :author has_many :author_categorizations, :through => :author, :source => :categorizations + has_many :author_addresses, :through => :author has_one :very_special_comment has_one :very_special_comment_with_post, :class_name => "VerySpecialComment", :include => :post @@ -57,6 +58,10 @@ class Post < ActiveRecord::Base end has_many :taggings_with_delete_all, :class_name => 'Tagging', :as => :taggable, :dependent => :delete_all + has_many :taggings_with_destroy, :class_name => 'Tagging', :as => :taggable, :dependent => :destroy + + has_many :tags_with_destroy, :through => :taggings, :source => :tag, :dependent => :destroy + has_many :tags_with_nullify, :through => :taggings, :source => :tag, :dependent => :nullify has_many :misc_tags, :through => :taggings, :source => :tag, :conditions => "tags.name = 'Misc'" has_many :funky_tags, :through => :taggings, :source => :tag diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 09c7b7ba63..665a4fe914 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -455,6 +455,10 @@ ActiveRecord::Schema.define do t.integer :comments_count, :default => 0 t.integer :taggings_count, :default => 0 t.integer :taggings_with_delete_all_count, :default => 0 + t.integer :taggings_with_destroy_count, :default => 0 + t.integer :tags_count, :default => 0 + t.integer :tags_with_destroy_count, :default => 0 + t.integer :tags_with_nullify_count, :default => 0 end create_table :price_estimates, :force => true do |t| -- cgit v1.2.3 From e62b57647258fad34129975c5a264d19af2dbbe8 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Sun, 6 Feb 2011 22:14:16 +0000 Subject: Refactor the implementations of AssociatioCollection#delete and #destroy to be more consistent with each other, and to stop passing blocks around, thus making the execution easier to follow. --- activerecord/test/cases/autosave_association_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index c2f2609c9e..dd2ce786aa 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -837,7 +837,7 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase @pirate.parrots.each { |parrot| parrot.mark_for_destruction } assert @pirate.save - assert_queries(1) do + assert_no_queries do assert @pirate.save end end -- cgit v1.2.3 From 2b4de6621f75b49c30c03ddd78076f7204cc9577 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 7 Feb 2011 16:09:33 -0800 Subject: require tag since we need it for this test --- activerecord/test/cases/associations/eager_load_nested_include_test.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/eager_load_nested_include_test.rb b/activerecord/test/cases/associations/eager_load_nested_include_test.rb index 8957586189..2cf9f89c3c 100644 --- a/activerecord/test/cases/associations/eager_load_nested_include_test.rb +++ b/activerecord/test/cases/associations/eager_load_nested_include_test.rb @@ -1,5 +1,6 @@ require 'cases/helper' require 'models/post' +require 'models/tag' require 'models/author' require 'models/comment' require 'models/category' -- cgit v1.2.3 From 9643243204fab063630380f42fcd4b8160044104 Mon Sep 17 00:00:00 2001 From: Jan Date: Thu, 3 Feb 2011 20:57:14 +0800 Subject: make set_table_name take effect immediately --- activerecord/test/cases/base_test.rb | 11 +++++++++++ activerecord/test/models/joke.rb | 4 ++++ activerecord/test/schema/schema.rb | 4 ++++ 3 files changed, 19 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 68adeff882..1fa5d2ac5f 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -20,6 +20,7 @@ require 'models/warehouse_thing' require 'models/parrot' require 'models/loose_person' require 'models/edge' +require 'models/joke' require 'rexml/document' require 'active_support/core_ext/exception' @@ -1156,6 +1157,16 @@ class BasicsTest < ActiveRecord::TestCase assert_equal "bar", k.table_name end + def test_switching_between_table_name + assert_difference("GoodJoke.count") do + Joke.set_table_name "cold_jokes" + Joke.create + + Joke.set_table_name "funny_jokes" + Joke.create + end + end + def test_quoted_table_name_after_set_table_name klass = Class.new(ActiveRecord::Base) diff --git a/activerecord/test/models/joke.rb b/activerecord/test/models/joke.rb index 3978abc2ba..d7f01e59e6 100644 --- a/activerecord/test/models/joke.rb +++ b/activerecord/test/models/joke.rb @@ -1,3 +1,7 @@ class Joke < ActiveRecord::Base set_table_name 'funny_jokes' end + +class GoodJoke < ActiveRecord::Base + set_table_name 'funny_jokes' +end diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 665a4fe914..b1763ff431 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -229,6 +229,10 @@ ActiveRecord::Schema.define do t.string :name end + create_table :cold_jokes, :force => true do |t| + t.string :name + end + create_table :goofy_string_id, :force => true, :id => false do |t| t.string :id, :null => false t.string :info -- cgit v1.2.3 From cd440236ad8a14d7430f65f1f4a878d5e04d6e22 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 8 Feb 2011 11:31:46 -0800 Subject: this test requires the job model, so we should require it --- activerecord/test/cases/locking_test.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb index 2a72838d06..3ce65a5b6b 100644 --- a/activerecord/test/cases/locking_test.rb +++ b/activerecord/test/cases/locking_test.rb @@ -1,6 +1,7 @@ require 'thread' require "cases/helper" require 'models/person' +require 'models/job' require 'models/reader' require 'models/legacy_thing' require 'models/reference' -- cgit v1.2.3 From 8ce57652b224c01d474ef20b27ea3c3838534467 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 8 Feb 2011 13:13:04 -0800 Subject: ignore max identifier length queries from pg --- activerecord/test/cases/helper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 1019ea1dda..7e9007ef73 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -51,7 +51,7 @@ end module ActiveRecord class SQLCounter - IGNORED_SQL = [/^PRAGMA (?!(table_info))/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/] + IGNORED_SQL = [/^PRAGMA (?!(table_info))/, /^SELECT currval/, /^SELECT CAST/, /^SELECT @@IDENTITY/, /^SELECT @@ROWCOUNT/, /^SAVEPOINT/, /^ROLLBACK TO SAVEPOINT/, /^RELEASE SAVEPOINT/, /^SHOW max_identifier_length/] # FIXME: this needs to be refactored so specific database can add their own # ignored SQL. This ignored SQL is for Oracle. -- cgit v1.2.3 From 0b58a7ff420d7ef4b643c521a62be7259dd2f5cb Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 7 Dec 2010 09:49:37 -0800 Subject: limit() should sanitize limit values This fixes CVE-2011-0448 --- activerecord/test/cases/base_test.rb | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 1fa5d2ac5f..1730d9fb56 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -54,6 +54,40 @@ class BasicsTest < ActiveRecord::TestCase assert_nil Edge.primary_key end + def test_limit_with_comma + assert_nothing_raised do + Topic.limit("1,2").all + end + end + + def test_limit_without_comma + assert_nothing_raised do + assert_equal 1, Topic.limit("1").all.length + end + + assert_nothing_raised do + assert_equal 1, Topic.limit(1).all.length + end + end + + def test_invalid_limit + assert_raises(ArgumentError) do + Topic.limit("asdfadf").all + end + end + + def test_limit_should_sanitize_sql_injection_for_limit_without_comas + assert_raises(ArgumentError) do + Topic.limit("1 select * from schema").all + end + end + + def test_limit_should_sanitize_sql_injection_for_limit_with_comas + assert_raises(ArgumentError) do + Topic.limit("1, 7 procedure help()").all + end + end + def test_select_symbol topic_ids = Topic.select(:id).map(&:id).sort assert_equal Topic.find(:all).map(&:id).sort, topic_ids -- cgit v1.2.3 From 1c6f4562d788cd5b63889b9597bc1765a1bd75e0 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 8 Feb 2011 16:01:16 -0800 Subject: primary keys should not be cleared on cache clear, fixing oracle tests --- activerecord/test/cases/base_test.rb | 5 +++++ activerecord/test/cases/connection_pool_test.rb | 4 +--- 2 files changed, 6 insertions(+), 3 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 1730d9fb56..20a16cc8ac 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -50,6 +50,11 @@ class Boolean < ActiveRecord::Base; end class BasicsTest < ActiveRecord::TestCase fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts + def test_columns_should_obey_set_primary_key + pk = Subscriber.columns.find { |x| x.name == 'nick' } + assert pk.primary, 'nick should be primary key' + end + def test_primary_key_with_no_id assert_nil Edge.primary_key end diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb index 55ac1bc406..0c545b7e9d 100644 --- a/activerecord/test/cases/connection_pool_test.rb +++ b/activerecord/test/cases/connection_pool_test.rb @@ -18,16 +18,14 @@ module ActiveRecord assert_equal columns_hash, @pool.columns_hash['posts'] end - def test_clearing_cache + def test_clearing_column_cache @pool.columns['posts'] @pool.columns_hash['posts'] - @pool.primary_keys['posts'] @pool.clear_cache! assert_equal 0, @pool.columns.size assert_equal 0, @pool.columns_hash.size - assert_equal 0, @pool.primary_keys.size end def test_primary_key -- cgit v1.2.3 From 5046120b97f4ce8ab08ff7e65c87cfb35f95dba6 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 8 Feb 2011 16:44:52 -0800 Subject: comma limits do not make sense on oracle or pg --- activerecord/test/cases/base_test.rb | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 20a16cc8ac..2cbff6a5e1 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -59,9 +59,11 @@ class BasicsTest < ActiveRecord::TestCase assert_nil Edge.primary_key end - def test_limit_with_comma - assert_nothing_raised do - Topic.limit("1,2").all + unless current_adapter?(:PostgreSQLAdapter) || current_adapter?(:OracleAdapter) + def test_limit_with_comma + assert_nothing_raised do + Topic.limit("1,2").all + end end end -- cgit v1.2.3 From 56fb3b1594d97fa00dd8d8d95f1d5bf7c30380ee Mon Sep 17 00:00:00 2001 From: Ken Collins Date: Wed, 9 Feb 2011 11:07:25 -0500 Subject: Allow limit values to accept an ARel SQL literal. --- activerecord/test/cases/base_test.rb | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 2cbff6a5e1..5b162f4f6f 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -59,7 +59,7 @@ class BasicsTest < ActiveRecord::TestCase assert_nil Edge.primary_key end - unless current_adapter?(:PostgreSQLAdapter) || current_adapter?(:OracleAdapter) + unless current_adapter?(:PostgreSQLAdapter,:OracleAdapter,:SQLServerAdapter) def test_limit_with_comma assert_nothing_raised do Topic.limit("1,2").all @@ -94,7 +94,13 @@ class BasicsTest < ActiveRecord::TestCase Topic.limit("1, 7 procedure help()").all end end - + + unless current_adapter?(:MysqlAdapter) + def test_limit_should_allow_sql_literal + assert_equal 1, Topic.limit(Arel.sql('2-1')).all.length + end + end + def test_select_symbol topic_ids = Topic.select(:id).map(&:id).sort assert_equal Topic.find(:all).map(&:id).sort, topic_ids -- cgit v1.2.3 From c567ccbb1738969345b29297e40a9aee87a97391 Mon Sep 17 00:00:00 2001 From: Raimonds Simanovskis Date: Wed, 9 Feb 2011 13:11:06 +0200 Subject: bugfix for serialized_attributes to be class specific previously serialized_attributes were kept as class attribute of ActiveRecord::Base - if some attribute was defined as serialized in one subclass then it was serialized in all other subclasses as well (if it had the same name) --- activerecord/test/cases/attribute_methods_test.rb | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb index 88eaea62e8..dfacf58da8 100644 --- a/activerecord/test/cases/attribute_methods_test.rb +++ b/activerecord/test/cases/attribute_methods_test.rb @@ -8,6 +8,7 @@ require 'models/topic' require 'models/company' require 'models/category' require 'models/reply' +require 'models/contact' class AttributeMethodsTest < ActiveRecord::TestCase fixtures :topics, :developers, :companies, :computers @@ -609,6 +610,10 @@ class AttributeMethodsTest < ActiveRecord::TestCase Object.send(:undef_method, :title) # remove test method from object end + def test_list_of_serialized_attributes + assert_equal %w(content), Topic.serialized_attributes.keys + assert_equal %w(preferences), Contact.serialized_attributes.keys + end private def cached_columns -- cgit v1.2.3 From d3b2596884d884b72d50de2b7ced6097df670736 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 9 Feb 2011 11:50:53 -0800 Subject: use parenthesis so limit works on all dbs --- activerecord/test/cases/base_test.rb | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 5b162f4f6f..ef6b741acd 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -94,13 +94,11 @@ class BasicsTest < ActiveRecord::TestCase Topic.limit("1, 7 procedure help()").all end end - - unless current_adapter?(:MysqlAdapter) - def test_limit_should_allow_sql_literal - assert_equal 1, Topic.limit(Arel.sql('2-1')).all.length - end + + def test_limit_should_allow_sql_literal + assert_equal 1, Topic.limit(Arel.sql('(2 - 1)')).all.length end - + def test_select_symbol topic_ids = Topic.select(:id).map(&:id).sort assert_equal Topic.find(:all).map(&:id).sort, topic_ids -- cgit v1.2.3 From 8bc464c8090f2929917ecd2d9476c914aa6da787 Mon Sep 17 00:00:00 2001 From: Franck Verrot Date: Sat, 27 Nov 2010 11:14:26 +0100 Subject: The optimistic lock column should be increased when calling touch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Santiago Pastorino and José Ignacio Costa --- activerecord/test/cases/locking_test.rb | 8 ++++++++ activerecord/test/schema/schema.rb | 1 + 2 files changed, 9 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb index 3ce65a5b6b..636a709924 100644 --- a/activerecord/test/cases/locking_test.rb +++ b/activerecord/test/cases/locking_test.rb @@ -99,6 +99,14 @@ class OptimisticLockingTest < ActiveRecord::TestCase assert_equal 1, p1.lock_version end + def test_touch_existing_lock + p1 = Person.find(1) + assert_equal 0, p1.lock_version + + p1.touch + assert_equal 1, p1.lock_version + end + def test_lock_column_name_existing t1 = LegacyThing.find(1) diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index b1763ff431..0b3865fc78 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -430,6 +430,7 @@ ActiveRecord::Schema.define do t.references :number1_fan t.integer :lock_version, :null => false, :default => 0 t.string :comments + t.timestamps end create_table :pets, :primary_key => :pet_id ,:force => true do |t| -- cgit v1.2.3 From 5548e47adbb6dda320cd09ecb696c568896aa6f1 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 9 Feb 2011 13:35:26 -0800 Subject: rawr, mysql, mysql2, why do you hate me. :'( --- activerecord/test/cases/base_test.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index ef6b741acd..6a61dcdb47 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -95,8 +95,10 @@ class BasicsTest < ActiveRecord::TestCase end end - def test_limit_should_allow_sql_literal - assert_equal 1, Topic.limit(Arel.sql('(2 - 1)')).all.length + unless current_adapter?(:MysqlAdapter) || current_adapter?(:Mysql2Adapter) + def test_limit_should_allow_sql_literal + assert_equal 1, Topic.limit(Arel.sql('2-1')).all.length + end end def test_select_symbol -- cgit v1.2.3 From 028016ede382de80b9e91a7e13cd5372c2afd4bd Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Thu, 10 Feb 2011 09:56:50 -0800 Subject: test cases for bind parameter logging --- activerecord/test/cases/bind_parameter_test.rb | 56 ++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 activerecord/test/cases/bind_parameter_test.rb (limited to 'activerecord/test') diff --git a/activerecord/test/cases/bind_parameter_test.rb b/activerecord/test/cases/bind_parameter_test.rb new file mode 100644 index 0000000000..4532ab6213 --- /dev/null +++ b/activerecord/test/cases/bind_parameter_test.rb @@ -0,0 +1,56 @@ +require 'cases/helper' +require 'models/topic' + +module ActiveRecord + class BindParameterTest < ActiveRecord::TestCase + class LogListener + attr_accessor :calls + + def initialize + @calls = [] + end + + def call(*args) + calls << args + end + end + + fixtures :topics + + def setup + super + @connection = ActiveRecord::Base.connection + @listener = LogListener.new + @pk = Topic.columns.find { |c| c.primary } + ActiveSupport::Notifications.subscribe('sql.active_record', @listener) + end + + def teardown + ActiveSupport::Notifications.unsubscribe(@listener) + end + + def test_binds_are_logged + # FIXME: use skip with minitest + return unless @connection.supports_statement_cache? + + sub = @connection.substitute_for(@pk, []) + binds = [[@pk, 1]] + sql = "select * from topics where id = #{sub}" + + @connection.exec_query(sql, 'SQL', binds) + + message = @listener.calls.find { |args| args[4][:sql] == sql } + assert_equal binds, message[4][:binds] + end + + def test_find_one_uses_binds + # FIXME: use skip with minitest + return unless @connection.supports_statement_cache? + + Topic.find(1) + binds = [[@pk, 1]] + message = @listener.calls.find { |args| args[4][:binds] == binds } + assert message, 'expected a message with binds' + end + end +end -- cgit v1.2.3 From 2f49cd91b7fdf18a559216fa725d039a5cd78ff1 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Thu, 10 Feb 2011 13:34:33 -0800 Subject: bind parameters are logged to debug log --- activerecord/test/cases/bind_parameter_test.rb | 38 ++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/bind_parameter_test.rb b/activerecord/test/cases/bind_parameter_test.rb index 4532ab6213..83001f44f9 100644 --- a/activerecord/test/cases/bind_parameter_test.rb +++ b/activerecord/test/cases/bind_parameter_test.rb @@ -3,6 +3,8 @@ require 'models/topic' module ActiveRecord class BindParameterTest < ActiveRecord::TestCase + fixtures :topics + class LogListener attr_accessor :calls @@ -15,8 +17,6 @@ module ActiveRecord end end - fixtures :topics - def setup super @connection = ActiveRecord::Base.connection @@ -52,5 +52,39 @@ module ActiveRecord message = @listener.calls.find { |args| args[4][:binds] == binds } assert message, 'expected a message with binds' end + + def test_logs_bind_vars + # FIXME: use skip with minitest + return unless @connection.supports_statement_cache? + + pk = Topic.columns.find { |x| x.primary } + + payload = { + :name => 'SQL', + :sql => 'select * from topics where id = ?', + :binds => [[pk, 10]] + } + event = ActiveSupport::Notifications::Event.new( + 'foo', + Time.now, + Time.now, + 123, + payload) + + logger = Class.new(ActiveRecord::LogSubscriber) { + attr_reader :debugs + def initialize + super + @debugs = [] + end + + def debug str + @debugs << str + end + }.new + + logger.sql event + assert_match("{#{pk.name.inspect} => #{10.inspect}}", logger.debugs.first) + end end end -- cgit v1.2.3 From 61b69338b27e3d865d4ca87269a7c12a74ea32da Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Thu, 10 Feb 2011 13:54:29 -0800 Subject: simplify bind parameter logging --- activerecord/test/cases/bind_parameter_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/bind_parameter_test.rb b/activerecord/test/cases/bind_parameter_test.rb index 83001f44f9..eb2991437b 100644 --- a/activerecord/test/cases/bind_parameter_test.rb +++ b/activerecord/test/cases/bind_parameter_test.rb @@ -84,7 +84,7 @@ module ActiveRecord }.new logger.sql event - assert_match("{#{pk.name.inspect} => #{10.inspect}}", logger.debugs.first) + assert_match({pk.name => 10}.inspect, logger.debugs.first) end end end -- cgit v1.2.3 From 339ad0d0020cf7173ef7debe32f3cbb8809de5ca Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Thu, 10 Feb 2011 14:17:09 -0800 Subject: fixing tests on 1.8, using a list of lists because order is important --- activerecord/test/cases/bind_parameter_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/bind_parameter_test.rb b/activerecord/test/cases/bind_parameter_test.rb index eb2991437b..19383bb06b 100644 --- a/activerecord/test/cases/bind_parameter_test.rb +++ b/activerecord/test/cases/bind_parameter_test.rb @@ -84,7 +84,7 @@ module ActiveRecord }.new logger.sql event - assert_match({pk.name => 10}.inspect, logger.debugs.first) + assert_match([[pk.name, 10]].inspect, logger.debugs.first) end end end -- cgit v1.2.3 From 83dd6e1e620e0350c5999bd35d75251374aceaea Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 11 Feb 2011 10:03:37 -0800 Subject: favor composition over inheritence. use AS::OrderedHash rather than omap --- activerecord/test/cases/fixtures_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb index 864a7a2acc..6dbdf4ca54 100644 --- a/activerecord/test/cases/fixtures_test.rb +++ b/activerecord/test/cases/fixtures_test.rb @@ -245,7 +245,7 @@ if Account.connection.respond_to?(:reset_pk_sequence!) def test_create_fixtures_resets_sequences_when_not_cached @instances.each do |instance| - max_id = create_fixtures(instance.class.table_name).inject(0) do |_max_id, (_, fixture)| + max_id = create_fixtures(instance.class.table_name).fixtures.inject(0) do |_max_id, (_, fixture)| fixture_id = fixture['id'].to_i fixture_id > _max_id ? fixture_id : _max_id end -- cgit v1.2.3 From fb09d025429d1c1f05a705a231edb9938ccff9b0 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 11 Feb 2011 14:33:03 -0800 Subject: refactor fixtures to do less work in the constructor --- activerecord/test/cases/helper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 7e9007ef73..be508e46f8 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -94,7 +94,7 @@ class ActiveSupport::TestCase self.use_transactional_fixtures = true def create_fixtures(*table_names, &block) - Fixtures.create_fixtures(ActiveSupport::TestCase.fixture_path, table_names, {}, &block) + Fixtures.create_fixtures(ActiveSupport::TestCase.fixture_path, table_names, fixture_class_names, &block) end end -- cgit v1.2.3 From 634424665422bc885c5e3f168908ea58e1f3c811 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 11 Feb 2011 16:09:34 -0800 Subject: create_fixtures() should always return a list --- activerecord/test/cases/fixtures_test.rb | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb index 6dbdf4ca54..ee51692f93 100644 --- a/activerecord/test/cases/fixtures_test.rb +++ b/activerecord/test/cases/fixtures_test.rb @@ -35,7 +35,7 @@ class FixturesTest < ActiveRecord::TestCase def test_clean_fixtures FIXTURES.each do |name| fixtures = nil - assert_nothing_raised { fixtures = create_fixtures(name) } + assert_nothing_raised { fixtures = create_fixtures(name).first } assert_kind_of(Fixtures, fixtures) fixtures.each { |_name, fixture| fixture.each { |key, value| @@ -53,7 +53,7 @@ class FixturesTest < ActiveRecord::TestCase end def test_attributes - topics = create_fixtures("topics") + topics = create_fixtures("topics").first assert_equal("The First Topic", topics["first"]["title"]) assert_nil(topics["second"]["author_email_address"]) end @@ -127,7 +127,7 @@ class FixturesTest < ActiveRecord::TestCase end def test_instantiation - topics = create_fixtures("topics") + topics = create_fixtures("topics").first assert_kind_of Topic, topics["first"].find end @@ -245,7 +245,7 @@ if Account.connection.respond_to?(:reset_pk_sequence!) def test_create_fixtures_resets_sequences_when_not_cached @instances.each do |instance| - max_id = create_fixtures(instance.class.table_name).fixtures.inject(0) do |_max_id, (_, fixture)| + max_id = create_fixtures(instance.class.table_name).first.fixtures.inject(0) do |_max_id, (_, fixture)| fixture_id = fixture['id'].to_i fixture_id > _max_id ? fixture_id : _max_id end @@ -509,7 +509,7 @@ class FasterFixturesTest < ActiveRecord::TestCase fixtures :categories, :authors def load_extra_fixture(name) - fixture = create_fixtures(name) + fixture = create_fixtures(name).first assert fixture.is_a?(Fixtures) @loaded_fixtures[fixture.table_name] = fixture end -- cgit v1.2.3 From d72add9c20778e253f90fbfe587eae0e205c40ad Mon Sep 17 00:00:00 2001 From: Ernie Miller Date: Sat, 12 Feb 2011 13:59:53 -0500 Subject: Fix table name collision due to incorrect alias count on certain joins. [#6423 state:committed] Signed-off-by: Santiago Pastorino --- .../test/cases/associations/inner_join_association_test.rb | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb index da2a81e98a..8f32902c19 100644 --- a/activerecord/test/cases/associations/inner_join_association_test.rb +++ b/activerecord/test/cases/associations/inner_join_association_test.rb @@ -16,6 +16,13 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase assert_equal authors(:david), result.first end + def test_construct_finder_sql_does_not_table_name_collide_on_duplicate_associations + assert_nothing_raised do + sql = Person.joins(:agents => {:agents => :agents}).joins(:agents => {:agents => {:primary_contact => :agents}}).to_sql + assert_match(/agents_people_4/i, sql) + end + end + def test_construct_finder_sql_ignores_empty_joins_hash sql = Author.joins({}).to_sql assert_no_match(/JOIN/i, sql) -- cgit v1.2.3 From fbd917f50a6046d02dd6a64ccfb1aed0cbce68d8 Mon Sep 17 00:00:00 2001 From: Ernie Miller Date: Thu, 10 Feb 2011 14:03:25 -0500 Subject: Remove Relation#& alias for Relation#merge --- activerecord/test/cases/method_scoping_test.rb | 2 +- activerecord/test/cases/relation_scoping_test.rb | 4 ++-- activerecord/test/cases/relations_test.rb | 14 +++++++------- 3 files changed, 10 insertions(+), 10 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/method_scoping_test.rb b/activerecord/test/cases/method_scoping_test.rb index e3ba65b4fa..7e8383da9e 100644 --- a/activerecord/test/cases/method_scoping_test.rb +++ b/activerecord/test/cases/method_scoping_test.rb @@ -227,7 +227,7 @@ class MethodScopingTest < ActiveRecord::TestCase end def test_scoped_create_with_join_and_merge - (Comment.where(:body => "but Who's Buying?").joins(:post) & Post.where(:body => 'Peace Sells...')).with_scope do + Comment.where(:body => "but Who's Buying?").joins(:post).merge(Post.where(:body => 'Peace Sells...')).with_scope do assert_equal({:body => "but Who's Buying?"}, Comment.scoped.scope_for_create) end end diff --git a/activerecord/test/cases/relation_scoping_test.rb b/activerecord/test/cases/relation_scoping_test.rb index 1bdf3136d4..cda2850b02 100644 --- a/activerecord/test/cases/relation_scoping_test.rb +++ b/activerecord/test/cases/relation_scoping_test.rb @@ -488,8 +488,8 @@ class DefaultScopingTest < ActiveRecord::TestCase end def test_create_with_merge - aaron = (PoorDeveloperCalledJamis.create_with(:name => 'foo', :salary => 20) & - PoorDeveloperCalledJamis.create_with(:name => 'Aaron')).new + aaron = PoorDeveloperCalledJamis.create_with(:name => 'foo', :salary => 20).merge( + PoorDeveloperCalledJamis.create_with(:name => 'Aaron')).new assert_equal 20, aaron.salary assert_equal 'Aaron', aaron.name diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 5018b16b67..184e7a2b9e 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -545,17 +545,17 @@ class RelationTest < ActiveRecord::TestCase end def test_relation_merging - devs = Developer.where("salary >= 80000") & Developer.limit(2) & Developer.order('id ASC').where("id < 3") + devs = Developer.where("salary >= 80000").merge(Developer.limit(2)).merge(Developer.order('id ASC').where("id < 3")) assert_equal [developers(:david), developers(:jamis)], devs.to_a - dev_with_count = Developer.limit(1) & Developer.order('id DESC') & Developer.select('developers.*') + dev_with_count = Developer.limit(1).merge(Developer.order('id DESC')).merge(Developer.select('developers.*')) assert_equal [developers(:poor_jamis)], dev_with_count.to_a end def test_relation_merging_with_eager_load relations = [] - relations << (Post.order('comments.id DESC') & Post.eager_load(:last_comment) & Post.scoped) - relations << (Post.eager_load(:last_comment) & Post.order('comments.id DESC') & Post.scoped) + relations << Post.order('comments.id DESC').merge(Post.eager_load(:last_comment)).merge(Post.scoped) + relations << Post.eager_load(:last_comment).merge(Post.order('comments.id DESC')).merge(Post.scoped) relations.each do |posts| post = posts.find { |p| p.id == 1 } @@ -564,18 +564,18 @@ class RelationTest < ActiveRecord::TestCase end def test_relation_merging_with_locks - devs = Developer.lock.where("salary >= 80000").order("id DESC") & Developer.limit(2) + devs = Developer.lock.where("salary >= 80000").order("id DESC").merge(Developer.limit(2)) assert_present devs.locked end def test_relation_merging_with_preload - [Post.scoped & Post.preload(:author), Post.preload(:author) & Post.scoped].each do |posts| + [Post.scoped.merge(Post.preload(:author)), Post.preload(:author).merge(Post.scoped)].each do |posts| assert_queries(2) { assert posts.first.author } end end def test_relation_merging_with_joins - comments = Comment.joins(:post).where(:body => 'Thank you for the welcome') & Post.where(:body => 'Such a lovely day') + comments = Comment.joins(:post).where(:body => 'Thank you for the welcome').merge(Post.where(:body => 'Such a lovely day')) assert_equal 1, comments.count end -- cgit v1.2.3 From 9143032a108bd41121337c82416ba90f460d8214 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sun, 13 Feb 2011 02:38:31 -0200 Subject: Add missing require --- activerecord/test/cases/associations/inner_join_association_test.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb index 8f32902c19..e2228228a3 100644 --- a/activerecord/test/cases/associations/inner_join_association_test.rb +++ b/activerecord/test/cases/associations/inner_join_association_test.rb @@ -4,6 +4,7 @@ require 'models/comment' require 'models/author' require 'models/category' require 'models/categorization' +require 'models/person' require 'models/tagging' require 'models/tag' -- cgit v1.2.3 From a7e19b30ca71f62af516675023659be061b2b70a Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Fri, 11 Feb 2011 22:22:19 +0000 Subject: Add interpolation of association conditions back in, in the form of proc { ... } rather than instance_eval-ing strings --- activerecord/test/cases/associations/eager_test.rb | 8 ++++++++ .../has_and_belongs_to_many_associations_test.rb | 2 +- .../cases/associations/has_many_associations_test.rb | 1 - .../associations/has_many_through_associations_test.rb | 7 +++++++ .../cases/associations/has_one_associations_test.rb | 8 ++++++++ activerecord/test/cases/base_test.rb | 6 ------ activerecord/test/models/company.rb | 15 ++++++--------- activerecord/test/models/post.rb | 7 +++++++ activerecord/test/models/project.rb | 17 +++++++++-------- activerecord/test/models/tagging.rb | 1 + 10 files changed, 47 insertions(+), 25 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index 3074648d59..42dd612083 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -668,6 +668,14 @@ class EagerAssociationTest < ActiveRecord::TestCase assert_equal people(:david, :susan), Person.find(:all, :include => [:readers, :primary_contact, :number1_fan], :conditions => "number1_fans_people.first_name like 'M%'", :order => 'people.id', :limit => 2, :offset => 0) end + def test_preload_with_interpolation + post = Post.includes(:comments_with_interpolated_conditions).find(posts(:welcome).id) + assert_equal [comments(:greetings)], post.comments_with_interpolated_conditions + + post = Post.joins(:comments_with_interpolated_conditions).find(posts(:welcome).id) + assert_equal [comments(:greetings)], post.comments_with_interpolated_conditions + end + def test_polymorphic_type_condition post = Post.find(posts(:thinking).id, :include => :taggings) assert post.taggings.include?(taggings(:thinking_general)) diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index 5dd2c9861e..dc382c3007 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -72,7 +72,7 @@ class DeveloperWithCounterSQL < ActiveRecord::Base :join_table => "developers_projects", :association_foreign_key => "project_id", :foreign_key => "developer_id", - :counter_sql => 'SELECT COUNT(*) AS count_all FROM projects INNER JOIN developers_projects ON projects.id = developers_projects.project_id WHERE developers_projects.developer_id =#{id}' + :counter_sql => proc { "SELECT COUNT(*) AS count_all FROM projects INNER JOIN developers_projects ON projects.id = developers_projects.project_id WHERE developers_projects.developer_id =#{id}" } end class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 23b777ac6d..ad774eb9ce 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -279,7 +279,6 @@ class HasManyAssociationsTest < ActiveRecord::TestCase def test_counting_using_finder_sql assert_equal 2, Firm.find(4).clients_using_sql.count - assert_equal 2, Firm.find(4).clients_using_multiline_sql.count end def test_belongs_to_sanity diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index c58068ef75..73b1d6c500 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -711,4 +711,11 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase post.author_addresses.delete(address) assert post[:author_count].nil? end + + def test_interpolated_conditions + post = posts(:welcome) + assert !post.tags.empty? + assert_equal post.tags, post.interpolated_tags + assert_equal post.tags, post.interpolated_tags_2 + end end diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb index dbf6dfe20d..6b73a35905 100644 --- a/activerecord/test/cases/associations/has_one_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_associations_test.rb @@ -243,6 +243,14 @@ class HasOneAssociationsTest < ActiveRecord::TestCase firm.destroy end + def test_finding_with_interpolated_condition + firm = Firm.find(:first) + superior = firm.clients.create(:name => 'SuperiorCo') + superior.rating = 10 + superior.save + assert_equal 10, firm.clients_with_interpolated_conditions.first.rating + end + def test_assignment_before_child_saved firm = Firm.find(1) firm.account = a = Account.new("credit_limit" => 1000) diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 6a61dcdb47..0ad20bb9bc 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -1295,12 +1295,6 @@ class BasicsTest < ActiveRecord::TestCase assert_equal res6, res7 end - def test_interpolate_sql - assert_nothing_raised { Category.new.send(:interpolate_sql, 'foo@bar') } - assert_nothing_raised { Category.new.send(:interpolate_sql, 'foo bar) baz') } - assert_nothing_raised { Category.new.send(:interpolate_sql, 'foo bar} baz') } - end - def test_scoped_find_conditions scoped_developers = Developer.send(:with_scope, :find => { :conditions => 'salary > 90000' }) do Developer.find(:all, :conditions => 'id < 5') diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb index 3e219fbe4a..e0b30efd51 100644 --- a/activerecord/test/models/company.rb +++ b/activerecord/test/models/company.rb @@ -48,19 +48,16 @@ class Firm < Company has_many :dependent_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :destroy has_many :exclusively_dependent_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :delete_all has_many :limited_clients, :class_name => "Client", :limit => 1 + has_many :clients_with_interpolated_conditions, :class_name => "Client", :conditions => proc { "rating > #{rating}" } has_many :clients_like_ms, :conditions => "name = 'Microsoft'", :class_name => "Client", :order => "id" has_many :clients_like_ms_with_hash_conditions, :conditions => { :name => 'Microsoft' }, :class_name => "Client", :order => "id" - has_many :clients_using_sql, :class_name => "Client", :finder_sql => 'SELECT * FROM companies WHERE client_of = #{id}' - has_many :clients_using_multiline_sql, :class_name => "Client", :finder_sql => ' - SELECT - companies.* - FROM companies WHERE companies.client_of = #{id}' + has_many :clients_using_sql, :class_name => "Client", :finder_sql => proc { "SELECT * FROM companies WHERE client_of = #{id}" } has_many :clients_using_counter_sql, :class_name => "Client", - :finder_sql => 'SELECT * FROM companies WHERE client_of = #{id}', - :counter_sql => 'SELECT COUNT(*) FROM companies WHERE client_of = #{id}' + :finder_sql => proc { "SELECT * FROM companies WHERE client_of = #{id} " }, + :counter_sql => proc { "SELECT COUNT(*) FROM companies WHERE client_of = #{id}" } has_many :clients_using_zero_counter_sql, :class_name => "Client", - :finder_sql => 'SELECT * FROM companies WHERE client_of = #{id}', - :counter_sql => 'SELECT 0 FROM companies WHERE client_of = #{id}' + :finder_sql => proc { "SELECT * FROM companies WHERE client_of = #{id}" }, + :counter_sql => proc { "SELECT 0 FROM companies WHERE client_of = #{id}" } has_many :no_clients_using_counter_sql, :class_name => "Client", :finder_sql => 'SELECT * FROM companies WHERE client_of = 1000', :counter_sql => 'SELECT COUNT(*) FROM companies WHERE client_of = 1000' diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index fd8cd2244a..5f29196790 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -41,6 +41,9 @@ class Post < ActiveRecord::Base has_many :author_categorizations, :through => :author, :source => :categorizations has_many :author_addresses, :through => :author + has_many :comments_with_interpolated_conditions, :class_name => 'Comment', + :conditions => proc { ["#{"#{aliased_table_name}." rescue ""}body = ?", 'Thank you for the welcome'] } + has_one :very_special_comment has_one :very_special_comment_with_post, :class_name => "VerySpecialComment", :include => :post has_many :special_comments @@ -57,6 +60,10 @@ class Post < ActiveRecord::Base end end + has_many :interpolated_taggings, :class_name => 'Tagging', :as => :taggable, :conditions => proc { "1 = #{1}" } + has_many :interpolated_tags, :through => :taggings + has_many :interpolated_tags_2, :through => :interpolated_taggings, :source => :tag + has_many :taggings_with_delete_all, :class_name => 'Tagging', :as => :taggable, :dependent => :delete_all has_many :taggings_with_destroy, :class_name => 'Tagging', :as => :taggable, :dependent => :destroy diff --git a/activerecord/test/models/project.rb b/activerecord/test/models/project.rb index 8a53a8f803..efe1ce67da 100644 --- a/activerecord/test/models/project.rb +++ b/activerecord/test/models/project.rb @@ -7,14 +7,15 @@ class Project < ActiveRecord::Base has_and_belongs_to_many :developers_named_david, :class_name => "Developer", :conditions => "name = 'David'", :uniq => true has_and_belongs_to_many :developers_named_david_with_hash_conditions, :class_name => "Developer", :conditions => { :name => 'David' }, :uniq => true has_and_belongs_to_many :salaried_developers, :class_name => "Developer", :conditions => "salary > 0" - has_and_belongs_to_many :developers_with_finder_sql, :class_name => "Developer", :finder_sql => 'SELECT t.*, j.* FROM developers_projects j, developers t WHERE t.id = j.developer_id AND j.project_id = #{id} ORDER BY t.id' - has_and_belongs_to_many :developers_with_multiline_finder_sql, :class_name => "Developer", :finder_sql => ' - SELECT - t.*, j.* - FROM - developers_projects j, - developers t WHERE t.id = j.developer_id AND j.project_id = #{id} ORDER BY t.id' - has_and_belongs_to_many :developers_by_sql, :class_name => "Developer", :delete_sql => "DELETE FROM developers_projects WHERE project_id = \#{id} AND developer_id = \#{record.id}" + has_and_belongs_to_many :developers_with_finder_sql, :class_name => "Developer", :finder_sql => proc { "SELECT t.*, j.* FROM developers_projects j, developers t WHERE t.id = j.developer_id AND j.project_id = #{id} ORDER BY t.id" } + has_and_belongs_to_many :developers_with_multiline_finder_sql, :class_name => "Developer", :finder_sql => proc { + "SELECT + t.*, j.* + FROM + developers_projects j, + developers t WHERE t.id = j.developer_id AND j.project_id = #{id} ORDER BY t.id" + } + has_and_belongs_to_many :developers_by_sql, :class_name => "Developer", :delete_sql => proc { |record| "DELETE FROM developers_projects WHERE project_id = #{id} AND developer_id = #{record.id}" } has_and_belongs_to_many :developers_with_callbacks, :class_name => "Developer", :before_add => Proc.new {|o, r| o.developers_log << "before_adding#{r.id || ''}"}, :after_add => Proc.new {|o, r| o.developers_log << "after_adding#{r.id || ''}"}, :before_remove => Proc.new {|o, r| o.developers_log << "before_removing#{r.id}"}, diff --git a/activerecord/test/models/tagging.rb b/activerecord/test/models/tagging.rb index 33ffc623d7..231d2b5890 100644 --- a/activerecord/test/models/tagging.rb +++ b/activerecord/test/models/tagging.rb @@ -6,6 +6,7 @@ class Tagging < ActiveRecord::Base belongs_to :tag, :include => :tagging belongs_to :super_tag, :class_name => 'Tag', :foreign_key => 'super_tag_id' belongs_to :invalid_tag, :class_name => 'Tag', :foreign_key => 'tag_id' + belongs_to :interpolated_tag, :class_name => 'Tag', :foreign_key => :tag_id, :conditions => proc { "1 = #{1}" } belongs_to :taggable, :polymorphic => true, :counter_cache => true has_many :things, :through => :taggable end -- cgit v1.2.3 From eab5fb49f839bf19da4c31b35142f9e05d05ed2e Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Fri, 11 Feb 2011 22:32:21 +0000 Subject: Fix test/cases/connection_pool_test.rb for sqlite3 in-memory db --- activerecord/test/cases/connection_pool_test.rb | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb index 0c545b7e9d..7ac14fa8d6 100644 --- a/activerecord/test/cases/connection_pool_test.rb +++ b/activerecord/test/cases/connection_pool_test.rb @@ -6,6 +6,16 @@ module ActiveRecord def setup # Keep a duplicate pool so we do not bother others @pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec + + if in_memory_db? + # Separate connections to an in-memory database create an entirely new database, + # with an empty schema etc, so we just stub out this schema on the fly. + @pool.with_connection do |connection| + connection.create_table :posts do |t| + t.integer :cololumn + end + end + end end def test_pool_caches_columns -- cgit v1.2.3 From e4dac4750d4aed2356a6d76c11c592f031a47bdd Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 14 Feb 2011 16:01:47 -0800 Subject: removing irrelevant test --- .../test/cases/adapters/mysql/reserved_word_test.rb | 18 ------------------ 1 file changed, 18 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb index b5c938b14a..43015098c9 100644 --- a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb +++ b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb @@ -78,24 +78,6 @@ class MysqlReservedWordTest < ActiveRecord::TestCase self.use_instantiated_fixtures = true self.use_transactional_fixtures = false - #fixtures :group - - def test_fixtures - f = create_test_fixtures :select, :distinct, :group, :values, :distincts_selects - - assert_nothing_raised { - f.each do |x| - x.delete_existing_fixtures - end - } - - assert_nothing_raised { - f.each do |x| - x.insert_fixtures - end - } - end - #activerecord model class with reserved-word table name def test_activerecord_model create_test_fixtures :select, :distinct, :group, :values, :distincts_selects -- cgit v1.2.3 From c9f1ab5365319e087e1b010a3f90626a2b8f080b Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 14 Feb 2011 17:10:14 -0800 Subject: bad tests are bad --- .../test/cases/adapters/mysql2/reserved_word_test.rb | 18 ------------------ 1 file changed, 18 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb index 90d8b0d923..1efa7deaeb 100644 --- a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb +++ b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb @@ -78,24 +78,6 @@ class MysqlReservedWordTest < ActiveRecord::TestCase self.use_instantiated_fixtures = true self.use_transactional_fixtures = false - #fixtures :group - - def test_fixtures - f = create_test_fixtures :select, :distinct, :group, :values, :distincts_selects - - assert_nothing_raised { - f.each do |x| - x.delete_existing_fixtures - end - } - - assert_nothing_raised { - f.each do |x| - x.insert_fixtures - end - } - end - #activerecord model class with reserved-word table name def test_activerecord_model create_test_fixtures :select, :distinct, :group, :values, :distincts_selects -- cgit v1.2.3 From f1778eb44a71595dff271001ee19c7bf6d0a0101 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 15 Feb 2011 12:40:41 -0300 Subject: Run tests without IdentityMap when IM=false is given. --- activerecord/test/cases/associations/eager_test.rb | 14 +++++++------- .../associations/has_one_through_associations_test.rb | 4 ++-- activerecord/test/cases/associations/identity_map_test.rb | 4 ++++ activerecord/test/cases/helper.rb | 2 +- activerecord/test/cases/identity_map_test.rb | 4 ++++ activerecord/test/cases/relations_test.rb | 10 +++++----- 6 files changed, 23 insertions(+), 15 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index 650bb15b55..ca71cd8ed3 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -185,7 +185,7 @@ class EagerAssociationTest < ActiveRecord::TestCase author = authors(:david) post = author.post_about_thinking_with_last_comment last_comment = post.last_comment - author = assert_queries(2) { Author.find(author.id, :include => {:post_about_thinking_with_last_comment => :last_comment})} # find the author, then find the posts, then find the comments + author = assert_queries(ActiveRecord::IdentityMap.enabled? ? 2 : 3) { Author.find(author.id, :include => {:post_about_thinking_with_last_comment => :last_comment})} # find the author, then find the posts, then find the comments assert_no_queries do assert_equal post, author.post_about_thinking_with_last_comment assert_equal last_comment, author.post_about_thinking_with_last_comment.last_comment @@ -196,7 +196,7 @@ class EagerAssociationTest < ActiveRecord::TestCase post = posts(:welcome) author = post.author author_address = author.author_address - post = assert_queries(2) { Post.find(post.id, :include => {:author_with_address => :author_address}) } # find the post, then find the author, then find the address + post = assert_queries(ActiveRecord::IdentityMap.enabled? ? 2 : 3) { Post.find(post.id, :include => {:author_with_address => :author_address}) } # find the post, then find the author, then find the address assert_no_queries do assert_equal author, post.author_with_address assert_equal author_address, post.author_with_address.author_address @@ -817,18 +817,18 @@ class EagerAssociationTest < ActiveRecord::TestCase assert_equal [posts(:welcome)], posts assert_equal authors(:david), assert_no_queries { posts[0].author} - posts = assert_queries(1) do + posts = assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => [:comments], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id') end assert_equal [posts(:welcome)], posts assert_equal authors(:david), assert_no_queries { posts[0].author} - posts = assert_queries(1) do + posts = assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do Post.find(:all, :include => :author, :joins => {:taggings => :tag}, :conditions => "tags.name = 'General'", :order => 'posts.id') end assert_equal posts(:welcome, :thinking), posts - posts = assert_queries(1) do + posts = assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do Post.find(:all, :include => :author, :joins => {:taggings => {:tag => :taggings}}, :conditions => "taggings_tags.super_tag_id=2", :order => 'posts.id') end assert_equal posts(:welcome, :thinking), posts @@ -842,7 +842,7 @@ class EagerAssociationTest < ActiveRecord::TestCase assert_equal [posts(:welcome)], posts assert_equal authors(:david), assert_no_queries { posts[0].author} - posts = assert_queries(1) do + posts = assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => ["INNER JOIN comments on comments.post_id = posts.id"], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id') end assert_equal [posts(:welcome)], posts @@ -931,7 +931,7 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_preloading_empty_belongs_to_polymorphic t = Tagging.create!(:taggable_type => 'Post', :taggable_id => Post.maximum(:id) + 1, :tag => tags(:general)) - tagging = assert_queries(1) { Tagging.preload(:taggable).find(t.id) } + tagging = assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) { Tagging.preload(:taggable).find(t.id) } assert_no_queries { assert_nil tagging.taggable } end diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb index fc1db4e34b..c1abba9dbf 100644 --- a/activerecord/test/cases/associations/has_one_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb @@ -88,12 +88,12 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase # conditions on the through table assert_equal clubs(:moustache_club), Member.find(@member.id, :include => :favourite_club).favourite_club memberships(:membership_of_favourite_club).update_attribute(:favourite, false) - assert_equal nil, Member.find(@member.id, :include => :favourite_club).favourite_club.reload + assert_equal nil, Member.find(@member.id, :include => :favourite_club).reload.favourite_club # conditions on the source table assert_equal clubs(:moustache_club), Member.find(@member.id, :include => :hairy_club).hairy_club clubs(:moustache_club).update_attribute(:name, "Association of Clean-Shaven Persons") - assert_equal nil, Member.find(@member.id, :include => :hairy_club).hairy_club.reload + assert_equal nil, Member.find(@member.id, :include => :hairy_club).reload.hairy_club end def test_has_one_through_polymorphic_with_source_type diff --git a/activerecord/test/cases/associations/identity_map_test.rb b/activerecord/test/cases/associations/identity_map_test.rb index 3d3ae0594b..07dc3deff4 100644 --- a/activerecord/test/cases/associations/identity_map_test.rb +++ b/activerecord/test/cases/associations/identity_map_test.rb @@ -5,6 +5,10 @@ require 'models/post' class InverseHasManyIdentityMapTest < ActiveRecord::TestCase fixtures :authors, :posts + def setup + skip unless ActiveRecord::IdentityMap.enabled? + end + def test_parent_instance_should_be_shared_with_every_child_on_find m = Author.first is = m.posts diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index ad0430a92f..fd20f1b120 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -27,7 +27,7 @@ ActiveSupport::Deprecation.debug = true QUOTED_TYPE = ActiveRecord::Base.connection.quote_column_name('type') # Enable Identity Map for testing -ActiveRecord::IdentityMap.enabled = true +ActiveRecord::IdentityMap.enabled = (ENV['IM'] == "false" ? false : true) def current_adapter?(*types) types.any? do |type| diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index 74d4cb0bfb..bed464dbce 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -25,6 +25,10 @@ class IdentityMapTest < ActiveRecord::TestCase :developers_projects, :computers, :authors, :author_addresses, :posts, :tags, :taggings, :comments, :subscribers + def setup + skip unless ActiveRecord::IdentityMap.enabled? + end + ############################################################################## # Basic tests checking if IM is functioning properly on basic find operations# ############################################################################## diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 109cb2c6bc..cb217a65db 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -285,7 +285,7 @@ class RelationTest < ActiveRecord::TestCase assert posts.first.comments.first end - assert_queries(1) do + assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do posts = Post.preload(:comments).to_a assert posts.first.comments.first end @@ -295,12 +295,12 @@ class RelationTest < ActiveRecord::TestCase assert posts.first.author end - assert_queries(1) do + assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do posts = Post.preload(:author).to_a assert posts.first.author end - assert_queries(1) do + assert_queries(ActiveRecord::IdentityMap.enabled? ? 2 : 3) do posts = Post.preload(:author, :comments).to_a assert posts.first.author assert posts.first.comments.first @@ -313,7 +313,7 @@ class RelationTest < ActiveRecord::TestCase assert posts.first.comments.first end - assert_queries(1) do + assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 2) do posts = Post.scoped.includes(:comments) assert posts.first.comments.first end @@ -323,7 +323,7 @@ class RelationTest < ActiveRecord::TestCase assert posts.first.author end - assert_queries(1) do + assert_queries(ActiveRecord::IdentityMap.enabled? ? 2 : 3) do posts = Post.includes(:author, :comments).to_a assert posts.first.author assert posts.first.comments.first -- cgit v1.2.3 From 90a850aea4c2c04df22be0aaad1144468fcc8078 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Tue, 15 Feb 2011 12:43:15 -0300 Subject: Fix expected queries in relation tests. --- activerecord/test/cases/relations_test.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index cb217a65db..0e45f5a374 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -300,7 +300,7 @@ class RelationTest < ActiveRecord::TestCase assert posts.first.author end - assert_queries(ActiveRecord::IdentityMap.enabled? ? 2 : 3) do + assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 3) do posts = Post.preload(:author, :comments).to_a assert posts.first.author assert posts.first.comments.first @@ -323,7 +323,7 @@ class RelationTest < ActiveRecord::TestCase assert posts.first.author end - assert_queries(ActiveRecord::IdentityMap.enabled? ? 2 : 3) do + assert_queries(ActiveRecord::IdentityMap.enabled? ? 1 : 3) do posts = Post.includes(:author, :comments).to_a assert posts.first.author assert posts.first.comments.first -- cgit v1.2.3 From f83218561e41f2309e2cbbcf4cf18eacf6322d61 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 15 Feb 2011 10:48:01 -0800 Subject: fixing variable names, removing FixtureFile instances from test ivars --- activerecord/test/cases/fixtures_test.rb | 6 ------ 1 file changed, 6 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb index ee51692f93..71303b9c83 100644 --- a/activerecord/test/cases/fixtures_test.rb +++ b/activerecord/test/cases/fixtures_test.rb @@ -132,7 +132,6 @@ class FixturesTest < ActiveRecord::TestCase end def test_complete_instantiation - assert_equal 4, @topics.size assert_equal "The First Topic", @first.title end @@ -142,7 +141,6 @@ class FixturesTest < ActiveRecord::TestCase end def test_erb_in_fixtures - assert_equal 11, @developers.size assert_equal "fixture_5", @dev_5.name end @@ -199,7 +197,6 @@ class FixturesTest < ActiveRecord::TestCase end def test_binary_in_fixtures - assert_equal 1, @binaries.size data = File.open(ASSETS_ROOT + "/flowers.jpg", 'rb') { |f| f.read } data.force_encoding('ASCII-8BIT') if data.respond_to?(:force_encoding) data.freeze @@ -304,9 +301,6 @@ class FixturesWithoutInstanceInstantiationTest < ActiveRecord::TestCase def test_without_instance_instantiation assert !defined?(@first), "@first is not defined" - assert_not_nil @topics - assert_not_nil @developers - assert_not_nil @accounts end end -- cgit v1.2.3 From 8276a240207ab6906fa2a6d4635f093906fa3c10 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 15 Feb 2011 15:52:27 -0800 Subject: fixture methods can be overridden and super() is useful --- activerecord/test/cases/fixtures_test.rb | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb index 71303b9c83..fa40fad56d 100644 --- a/activerecord/test/cases/fixtures_test.rb +++ b/activerecord/test/cases/fixtures_test.rb @@ -378,6 +378,21 @@ class ForeignKeyFixturesTest < ActiveRecord::TestCase end end +class OverRideFixtureMethodTest < ActiveRecord::TestCase + fixtures :topics + + def topics(name) + topic = super + topic.title = 'omg' + topic + end + + def test_fixture_methods_can_be_overridden + x = topics :first + assert_equal 'omg', x.title + end +end + class CheckSetTableNameFixturesTest < ActiveRecord::TestCase set_fixture_class :funny_jokes => 'Joke' fixtures :funny_jokes -- cgit v1.2.3 From 9b188c5bfe04349aa8ee0eeb2b53456601b8c3fc Mon Sep 17 00:00:00 2001 From: Steven Fenigstein Date: Fri, 11 Feb 2011 00:39:58 -0800 Subject: removed an unnecessary second query when passing an ActiveRecord::Relation to a where clause. And added ability to use subselects in where clauses. --- activerecord/test/cases/relations_test.rb | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 184e7a2b9e..843c3d2d96 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -467,7 +467,7 @@ class RelationTest < ActiveRecord::TestCase authors = Author.find_by_id([author]) assert_equal author, authors end - + def test_find_all_using_where_twice_should_or_the_relation david = authors(:david) relation = Author.unscoped @@ -488,6 +488,33 @@ class RelationTest < ActiveRecord::TestCase end assert_equal [david], relation.all end + + def test_find_all_using_where_with_relation + david = authors(:david) + # switching the lines below would succeed in current rails + # assert_queries(2) { + assert_queries(1) { + relation = Author.where(:id => Author.where(:id => david.id)) + assert_equal [david], relation.all + } + end + + def test_find_all_using_where_with_relation_with_joins + david = authors(:david) + assert_queries(1) { + relation = Author.where(:id => Author.joins(:posts).where(:id => david.id)) + assert_equal [david], relation.all + } + end + + + def test_find_all_using_where_with_relation_with_select_to_build_subquery + david = authors(:david) + assert_queries(1) { + relation = Author.where(:name => Author.where(:id => david.id).select(:name)) + assert_equal [david], relation.all + } + end def test_exists davids = Author.where(:name => 'David') -- cgit v1.2.3 From 2e2e58a6a30d013f062157be6ae40617703adc8b Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 16 Feb 2011 11:08:01 -0800 Subject: fixing whitespace problems --- activerecord/test/cases/relations_test.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 843c3d2d96..1e84f5f92d 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -467,7 +467,7 @@ class RelationTest < ActiveRecord::TestCase authors = Author.find_by_id([author]) assert_equal author, authors end - + def test_find_all_using_where_twice_should_or_the_relation david = authors(:david) relation = Author.unscoped @@ -488,7 +488,7 @@ class RelationTest < ActiveRecord::TestCase end assert_equal [david], relation.all end - + def test_find_all_using_where_with_relation david = authors(:david) # switching the lines below would succeed in current rails @@ -507,7 +507,7 @@ class RelationTest < ActiveRecord::TestCase } end - + def test_find_all_using_where_with_relation_with_select_to_build_subquery david = authors(:david) assert_queries(1) { -- cgit v1.2.3 From 9c023cc4d2949d10fa6cfa013655d86aae8d8019 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 16 Feb 2011 15:11:48 -0800 Subject: explicitly allowing lolqueries --- activerecord/test/cases/relations_test.rb | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 1e84f5f92d..4b98cc9daf 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -474,10 +474,17 @@ class RelationTest < ActiveRecord::TestCase relation = relation.where(:name => david.name) relation = relation.where(:name => 'Santiago') relation = relation.where(:id => david.id) - assert_equal [david], relation.all + assert_equal [], relation.all end - def test_find_all_with_multiple_ors + def test_multi_where_ands_queries + relation = Author.unscoped + david = authors(:david) + sql = relation.where(:name => david.name).where(:name => 'Santiago').to_sql + assert_match('AND', sql) + end + + def test_find_all_with_multiple_should_use_and david = authors(:david) relation = [ { :name => david.name }, @@ -486,7 +493,7 @@ class RelationTest < ActiveRecord::TestCase ].inject(Author.unscoped) do |memo, param| memo.where(param) end - assert_equal [david], relation.all + assert_equal [], relation.all end def test_find_all_using_where_with_relation -- cgit v1.2.3 From f0b98050296b57d95dbc789f8e52fa82499d151a Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Mon, 14 Feb 2011 20:39:51 +0000 Subject: Ensure that association_ids uses the correct attribute where the association is a has_many :through with a :primary_key option on the source reflection. [#6376 state:resolved] --- .../cases/associations/has_many_through_associations_test.rb | 10 ++++++++++ activerecord/test/models/post.rb | 1 + 2 files changed, 11 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 73b1d6c500..7e77539fe7 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -718,4 +718,14 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase assert_equal post.tags, post.interpolated_tags assert_equal post.tags, post.interpolated_tags_2 end + + def test_primary_key_option_on_source + post = posts(:welcome) + category = categories(:general) + categorization = Categorization.create!(:post_id => post.id, :named_category_name => category.name) + + assert_equal [category], post.named_categories + assert_equal [category.name], post.named_category_ids # checks when target loaded + assert_equal [category.name], post.reload.named_category_ids # checks when target no loaded + end end diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index 5f29196790..1bbcab3a39 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -90,6 +90,7 @@ class Post < ActiveRecord::Base has_many :standard_categorizations, :class_name => 'Categorization', :foreign_key => :post_id has_many :author_using_custom_pk, :through => :standard_categorizations has_many :authors_using_custom_pk, :through => :standard_categorizations + has_many :named_categories, :through => :standard_categorizations has_many :readers has_many :readers_with_person, :include => :person, :class_name => "Reader" -- cgit v1.2.3 From 91fd6510563f84ee473bb217bc63ed598abe3f24 Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Mon, 14 Feb 2011 23:14:42 +0000 Subject: Allow building and then later saving has_many :through records, such that the join record is automatically saved too. This requires the :inverse_of option to be set on the source association in the join model. See the CHANGELOG for details. [#4329 state:resolved] --- .../associations/has_many_through_associations_test.rb | 18 ++++++++++++++++++ activerecord/test/models/person.rb | 2 ++ activerecord/test/models/post.rb | 1 + activerecord/test/models/reader.rb | 3 ++- 4 files changed, 23 insertions(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index 7e77539fe7..efdecd4b09 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -113,6 +113,24 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase assert posts(:thinking).reload.people(true).collect(&:first_name).include?("Ted") end + def test_build_then_save_with_has_many_inverse + post = posts(:thinking) + person = post.people.build(:first_name => "Bob") + person.save + post.reload + + assert post.people.include?(person) + end + + def test_build_then_save_with_has_one_inverse + post = posts(:thinking) + person = post.single_people.build(:first_name => "Bob") + person.save + post.reload + + assert post.single_people.include?(person) + end + def test_delete_association assert_queries(2){posts(:welcome);people(:michael); } diff --git a/activerecord/test/models/person.rb b/activerecord/test/models/person.rb index a18b9e44df..cc3a4f5f9d 100644 --- a/activerecord/test/models/person.rb +++ b/activerecord/test/models/person.rb @@ -1,5 +1,7 @@ class Person < ActiveRecord::Base has_many :readers + has_one :reader + has_many :posts, :through => :readers has_many :posts_with_no_comments, :through => :readers, :source => :post, :include => :comments, :conditions => 'comments.id is null' diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index 1bbcab3a39..a342aaf60b 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -95,6 +95,7 @@ class Post < ActiveRecord::Base has_many :readers has_many :readers_with_person, :include => :person, :class_name => "Reader" has_many :people, :through => :readers + has_many :single_people, :through => :readers has_many :people_with_callbacks, :source=>:person, :through => :readers, :before_add => lambda {|owner, reader| log(:added, :before, reader.first_name) }, :after_add => lambda {|owner, reader| log(:added, :after, reader.first_name) }, diff --git a/activerecord/test/models/reader.rb b/activerecord/test/models/reader.rb index 27527bf566..0207a2bd92 100644 --- a/activerecord/test/models/reader.rb +++ b/activerecord/test/models/reader.rb @@ -1,4 +1,5 @@ class Reader < ActiveRecord::Base belongs_to :post - belongs_to :person + belongs_to :person, :inverse_of => :readers + belongs_to :single_person, :class_name => 'Person', :foreign_key => :person_id, :inverse_of => :reader end -- cgit v1.2.3 From 1644663ba7f678d178deab2bf1629dc05626f85b Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Thu, 17 Feb 2011 23:55:05 +0000 Subject: Split AssociationProxy into an Association class (and subclasses) which manages the association, and a CollectionProxy class which is *only* a proxy. Singular associations no longer have a proxy. See CHANGELOG for more. --- .../cases/associations/association_proxy_test.rb | 52 ---------------------- .../associations/belongs_to_associations_test.rb | 13 +++--- .../associations/has_one_associations_test.rb | 9 +--- .../has_one_through_associations_test.rb | 4 +- .../associations/inverse_associations_test.rb | 41 +---------------- .../test/cases/associations/join_model_test.rb | 2 +- activerecord/test/cases/associations_test.rb | 36 --------------- .../test/cases/autosave_association_test.rb | 2 +- activerecord/test/cases/named_scope_test.rb | 2 +- activerecord/test/cases/nested_attributes_test.rb | 10 ++--- 10 files changed, 19 insertions(+), 152 deletions(-) delete mode 100644 activerecord/test/cases/associations/association_proxy_test.rb (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/association_proxy_test.rb b/activerecord/test/cases/associations/association_proxy_test.rb deleted file mode 100644 index 55d8da4c4e..0000000000 --- a/activerecord/test/cases/associations/association_proxy_test.rb +++ /dev/null @@ -1,52 +0,0 @@ -require "cases/helper" - -module ActiveRecord - module Associations - class AsssociationProxyTest < ActiveRecord::TestCase - class FakeOwner - attr_accessor :new_record - alias :new_record? :new_record - - def initialize - @new_record = false - end - end - - class FakeReflection < Struct.new(:options, :klass) - def initialize options = {}, klass = nil - super - end - - def check_validity! - true - end - end - - class FakeTarget - end - - class FakeTargetProxy < AssociationProxy - def association_scope - true - end - - def find_target - FakeTarget.new - end - end - - def test_method_missing_error - reflection = FakeReflection.new({}, Object.new) - owner = FakeOwner.new - proxy = FakeTargetProxy.new(owner, reflection) - - exception = assert_raises(NoMethodError) do - proxy.omg - end - - assert_match('omg', exception.message) - assert_match(FakeTarget.name, exception.message) - end - end - end -end diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index 01073bca3d..9006914508 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -50,11 +50,6 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase assert_nothing_raised { account.firm = account.firm } end - def test_triple_equality - assert Client.find(3).firm === Firm - assert Firm === Client.find(3).firm - end - def test_type_mismatch assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = 1 } assert_raise(ActiveRecord::AssociationTypeMismatch) { Account.find(1).firm = Project.find(1) } @@ -569,13 +564,15 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase def test_reloading_association_with_key_change client = companies(:second_client) - firm = client.firm # note this is a proxy object + firm = client.association(:firm) client.firm = companies(:another_firm) - assert_equal companies(:another_firm), firm.reload + firm.reload + assert_equal companies(:another_firm), firm.target client.client_of = companies(:first_firm).id - assert_equal companies(:first_firm), firm.reload + firm.reload + assert_equal companies(:first_firm), firm.target end def test_polymorphic_counter_cache diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb index 6b73a35905..c1dad5e246 100644 --- a/activerecord/test/cases/associations/has_one_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_associations_test.rb @@ -66,11 +66,6 @@ class HasOneAssociationsTest < ActiveRecord::TestCase assert_nothing_raised { company.account = company.account } end - def test_triple_equality - assert Account === companies(:first_firm).account - assert companies(:first_firm).account === Account - end - def test_type_mismatch assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).account = 1 } assert_raise(ActiveRecord::AssociationTypeMismatch) { companies(:first_firm).account = Project.find(1) } @@ -320,7 +315,7 @@ class HasOneAssociationsTest < ActiveRecord::TestCase def test_creation_failure_without_dependent_option pirate = pirates(:blackbeard) - orig_ship = pirate.ship.target + orig_ship = pirate.ship assert_equal ships(:black_pearl), orig_ship new_ship = pirate.create_ship @@ -333,7 +328,7 @@ class HasOneAssociationsTest < ActiveRecord::TestCase def test_creation_failure_with_dependent_option pirate = pirates(:blackbeard).becomes(DestructivePirate) - orig_ship = pirate.dependent_ship.target + orig_ship = pirate.dependent_ship new_ship = pirate.create_dependent_ship assert new_ship.new_record? diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb index 91d3025468..9ca5f88330 100644 --- a/activerecord/test/cases/associations/has_one_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb @@ -139,7 +139,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase def test_assigning_association_correctly_assigns_target new_member = Member.create(:name => "Chris") new_member.club = new_club = Club.create(:name => "LRUG") - assert_equal new_club, new_member.club.target + assert_equal new_club, new_member.association(:club).target end def test_has_one_through_proxy_should_not_respond_to_private_methods @@ -197,7 +197,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase MemberDetail.find(:all, :include => :member_type) end @new_detail = @member_details[0] - assert @new_detail.send(:association_proxy, :member_type).loaded? + assert @new_detail.send(:association, :member_type).loaded? assert_not_nil assert_no_queries { @new_detail.member_type } end diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb index e9a57a00a0..76282213d8 100644 --- a/activerecord/test/cases/associations/inverse_associations_test.rb +++ b/activerecord/test/cases/associations/inverse_associations_test.rb @@ -137,7 +137,7 @@ class InverseHasOneTests < ActiveRecord::TestCase def test_parent_instance_should_be_shared_with_newly_created_child_via_bang_method m = Man.find(:first) - f = m.face.create!(:description => 'haunted') + f = m.create_face!(:description => 'haunted') assert_not_nil f.man assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance" m.name = 'Bongo' @@ -158,18 +158,6 @@ class InverseHasOneTests < ActiveRecord::TestCase assert_equal m.name, f.man.name, "Name of man should be the same after changes to replaced-child-owned instance" end - def test_parent_instance_should_be_shared_with_replaced_via_method_child - m = Man.find(:first) - f = Face.new(:description => 'haunted') - m.face.replace(f) - assert_not_nil f.man - assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance" - m.name = 'Bongo' - assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance" - f.man.name = 'Mungo' - assert_equal m.name, f.man.name, "Name of man should be the same after changes to replaced-child-owned instance" - end - def test_trying_to_use_inverses_that_dont_exist_should_raise_an_error assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { Man.find(:first).dirty_face } end @@ -271,18 +259,6 @@ class InverseHasManyTests < ActiveRecord::TestCase assert_equal m.name, i.man.name, "Name of man should be the same after changes to replaced-child-owned instance" end - def test_parent_instance_should_be_shared_with_replaced_via_method_children - m = Man.find(:first) - i = Interest.new(:topic => 'Industrial Revolution Re-enactment') - m.interests.replace([i]) - assert_not_nil i.man - assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance" - m.name = 'Bongo' - assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance" - i.man.name = 'Mungo' - assert_equal m.name, i.man.name, "Name of man should be the same after changes to replaced-child-owned instance" - end - def test_trying_to_use_inverses_that_dont_exist_should_raise_an_error assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { Man.find(:first).secret_interests } end @@ -366,19 +342,6 @@ class InverseBelongsToTests < ActiveRecord::TestCase assert_equal f.description, m.face.description, "Description of face should be the same after changes to replaced-parent-owned instance" end - def test_child_instance_should_be_shared_with_replaced_via_method_parent - f = faces(:trusting) - assert_not_nil f.man - m = Man.new(:name => 'Charles') - f.man.replace(m) - assert_not_nil m.face - assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance" - f.description = 'gormless' - assert_equal f.description, m.face.description, "Description of face should be the same after changes to child instance" - m.face.description = 'pleasing' - assert_equal f.description, m.face.description, "Description of face should be the same after changes to replaced-parent-owned instance" - end - def test_trying_to_use_inverses_that_dont_exist_should_raise_an_error assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { Face.find(:first).horrible_man } end @@ -434,7 +397,7 @@ class InversePolymorphicBelongsToTests < ActiveRecord::TestCase new_man = Man.new assert_not_nil face.polymorphic_man - face.polymorphic_man.replace(new_man) + face.polymorphic_man = new_man assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same before changes to parent instance" face.description = 'Bongo' diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb index c50fcd3f33..0e2f4a33cc 100644 --- a/activerecord/test/cases/associations/join_model_test.rb +++ b/activerecord/test/cases/associations/join_model_test.rb @@ -153,7 +153,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase def test_create_polymorphic_has_one_with_scope old_count = Tagging.count - tagging = posts(:welcome).tagging.create(:tag => tags(:misc)) + tagging = posts(:welcome).create_tagging(:tag => tags(:misc)) assert_equal "Post", tagging.taggable_type assert_equal old_count+1, Tagging.count end diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb index 83c605d2bb..a1996fcf27 100644 --- a/activerecord/test/cases/associations_test.rb +++ b/activerecord/test/cases/associations_test.rb @@ -133,25 +133,6 @@ end class AssociationProxyTest < ActiveRecord::TestCase fixtures :authors, :posts, :categorizations, :categories, :developers, :projects, :developers_projects - def test_proxy_accessors - welcome = posts(:welcome) - assert_equal welcome, welcome.author.proxy_owner - assert_equal welcome.class.reflect_on_association(:author), welcome.author.proxy_reflection - welcome.author.class # force load target - assert_equal welcome.author, welcome.author.proxy_target - - david = authors(:david) - assert_equal david, david.posts.proxy_owner - assert_equal david.class.reflect_on_association(:posts), david.posts.proxy_reflection - david.posts.class # force load target - assert_equal david.posts, david.posts.proxy_target - - assert_equal david, david.posts_with_extension.testing_proxy_owner - assert_equal david.class.reflect_on_association(:posts_with_extension), david.posts_with_extension.testing_proxy_reflection - david.posts_with_extension.class # force load target - assert_equal david.posts_with_extension, david.posts_with_extension.testing_proxy_target - end - def test_push_does_not_load_target david = authors(:david) @@ -216,16 +197,6 @@ class AssociationProxyTest < ActiveRecord::TestCase assert_equal post.body, "More cool stuff!" end - def test_failed_reload_returns_nil - p = setup_dangling_association - assert_nil p.author.reload - end - - def test_failed_reset_returns_nil - p = setup_dangling_association - assert_nil p.author.reset - end - def test_reload_returns_assocition david = developers(:david) assert_nothing_raised do @@ -240,13 +211,6 @@ class AssociationProxyTest < ActiveRecord::TestCase [*author] end end - - def setup_dangling_association - josh = Author.create(:name => "Josh") - p = Post.create(:title => "New on Edge", :body => "More cool stuff!", :author => josh) - josh.destroy - p - end end class OverridingAssociationsTest < ActiveRecord::TestCase diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index dd2ce786aa..8998879261 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -112,7 +112,7 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas def test_build_before_child_saved firm = Firm.find(1) - account = firm.account.build("credit_limit" => 1000) + account = firm.build_account("credit_limit" => 1000) assert_equal account, firm.account assert !account.persisted? assert firm.save diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb index ed5e1e0cba..d05b0ff947 100644 --- a/activerecord/test/cases/named_scope_test.rb +++ b/activerecord/test/cases/named_scope_test.rb @@ -448,7 +448,7 @@ class NamedScopeTest < ActiveRecord::TestCase [:destroy_all, :reset, :delete_all].each do |method| before = post.comments.containing_the_letter_e - post.comments.send(method) + post.association(:comments).send(method) assert before.object_id != post.comments.containing_the_letter_e.object_id, "AssociationCollection##{method} should reset the named scopes cache" end end diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index d1afe7376a..c57ab7ed28 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -155,7 +155,7 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase man = Man.find man.id man.interests_attributes = [{:id => interest.id, :topic => 'gardening'}] assert_equal man.interests.first.topic, man.interests[0].topic - end + end end class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase @@ -918,16 +918,16 @@ class TestHasManyAutosaveAssociationWhichItselfHasAutosaveAssociations < ActiveR test "if association is not loaded and association record is saved and then in memory record attributes should be saved" do @ship.parts_attributes=[{:id => @part.id,:name =>'Deck'}] - assert_equal 1, @ship.parts.proxy_target.size + assert_equal 1, @ship.association(:parts).target.size assert_equal 'Deck', @ship.parts[0].name end test "if association is not loaded and child doesn't change and I am saving a grandchild then in memory record should be used" do @ship.parts_attributes=[{:id => @part.id,:trinkets_attributes =>[{:id => @trinket.id, :name => 'Ruby'}]}] - assert_equal 1, @ship.parts.proxy_target.size + assert_equal 1, @ship.association(:parts).target.size assert_equal 'Mast', @ship.parts[0].name - assert_no_difference("@ship.parts[0].trinkets.proxy_target.size") do - @ship.parts[0].trinkets.proxy_target.size + assert_no_difference("@ship.parts[0].association(:trinkets).target.size") do + @ship.parts[0].association(:trinkets).target.size end assert_equal 'Ruby', @ship.parts[0].trinkets[0].name @ship.save -- cgit v1.2.3 From 9a9d895481ada301143c0554dabd4ec9914b8703 Mon Sep 17 00:00:00 2001 From: Nicholas Rowe Date: Thu, 17 Feb 2011 20:46:52 -0500 Subject: Fix Typos: remove several occurences of the the --- activerecord/test/cases/autosave_association_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index 11c0c5b0ef..8688ebc617 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -747,7 +747,7 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase 2.times { |i| @pirate.send(association_name).create!(:name => "#{association_name}_#{i}") } before = @pirate.send(association_name).map { |c| c.mark_for_destruction ; c } - # Stub the destroy method of the the second child to raise an exception + # Stub the destroy method of the second child to raise an exception class << before.last def destroy(*args) super -- cgit v1.2.3 From 15a03ca9b0b9a3582ca0f7695ed87557eedc95fb Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Fri, 18 Feb 2011 15:38:00 -0300 Subject: No need to test against target anymore. --- activerecord/test/cases/identity_map_test.rb | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index bed464dbce..16da188476 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -105,15 +105,15 @@ class IdentityMapTest < ActiveRecord::TestCase assert_no_queries do comment.post end - assert_same post, comment.post.target + assert_same post, comment.post end def test_associated_object_are_assigned_from_identity_map post = Post.find(1) post.comments.each do |comment| - assert_same post, comment.post.target - assert_equal post.object_id, comment.post.target.object_id + assert_same post, comment.post + assert_equal post.object_id, comment.post.object_id end end @@ -176,7 +176,7 @@ class IdentityMapTest < ActiveRecord::TestCase pirate.reload pirate.birds_attributes = [{ :id => posideons.id, :name => 'Grace OMalley' }] - assert_equal 'Grace OMalley', pirate.birds.send(:load_target).find { |r| r.id == posideons.id }.name + assert_equal 'Grace OMalley', pirate.birds.send(:load).find { |r| r.id == posideons.id }.name end def test_changing_associations @@ -267,20 +267,20 @@ class IdentityMapTest < ActiveRecord::TestCase posts = Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => [:comments], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id') assert_equal [posts(:welcome)], posts assert_equal authors(:david), assert_no_queries { posts[0].author} - assert_same posts.first.author.target, Author.first + assert_same posts.first.author, Author.first posts = Post.find(:all, :select => 'distinct posts.*', :include => :author, :joins => [:comments], :conditions => "comments.body like 'Thank you%'", :order => 'posts.id') assert_equal [posts(:welcome)], posts assert_equal authors(:david), assert_no_queries { posts[0].author} - assert_same posts.first.author.target, Author.first + assert_same posts.first.author, Author.first posts = Post.find(:all, :include => :author, :joins => {:taggings => :tag}, :conditions => "tags.name = 'General'", :order => 'posts.id') assert_equal posts(:welcome, :thinking), posts - assert_same posts.first.author.target, Author.first + assert_same posts.first.author, Author.first posts = Post.find(:all, :include => :author, :joins => {:taggings => {:tag => :taggings}}, :conditions => "taggings_tags.super_tag_id=2", :order => 'posts.id') assert_equal posts(:welcome, :thinking), posts - assert_same posts.first.author.target, Author.first + assert_same posts.first.author, Author.first end def test_eager_loading_with_conditions_on_string_joined_table_preloads -- cgit v1.2.3 From b8c2feb97e3f0df38b6fd28b38eaab7df3a03984 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Fri, 18 Feb 2011 15:38:17 -0300 Subject: Use to_a instead :load in test, since :load changed. --- activerecord/test/cases/identity_map_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index 16da188476..6608802c23 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -176,7 +176,7 @@ class IdentityMapTest < ActiveRecord::TestCase pirate.reload pirate.birds_attributes = [{ :id => posideons.id, :name => 'Grace OMalley' }] - assert_equal 'Grace OMalley', pirate.birds.send(:load).find { |r| r.id == posideons.id }.name + assert_equal 'Grace OMalley', pirate.birds.to_a.find { |r| r.id == posideons.id }.name end def test_changing_associations -- cgit v1.2.3 From d21a454327d4f4751fc4fa6260f03f9961191336 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Fri, 18 Feb 2011 15:40:48 -0300 Subject: No need to test agaisnt target. --- activerecord/test/cases/associations/identity_map_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/identity_map_test.rb b/activerecord/test/cases/associations/identity_map_test.rb index 07dc3deff4..37ec3b846e 100644 --- a/activerecord/test/cases/associations/identity_map_test.rb +++ b/activerecord/test/cases/associations/identity_map_test.rb @@ -116,7 +116,7 @@ class InverseHasManyIdentityMapTest < ActiveRecord::TestCase m = Author.first i = Post.new(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum') m.posts = [i] - assert_same m, i.author.target + assert_same m, i.author assert_not_nil i.author assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance" m.name = 'Bongo' -- cgit v1.2.3 From eb23b2247d84df104bccb456b45e6e61b8157ef8 Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Fri, 18 Feb 2011 15:44:23 -0300 Subject: Should use "=" instead "replace" after this commit: 1644663ba7f678d178deab2bf1629dc05626f85b --- activerecord/test/cases/associations/identity_map_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/identity_map_test.rb b/activerecord/test/cases/associations/identity_map_test.rb index 37ec3b846e..73ea13fa7a 100644 --- a/activerecord/test/cases/associations/identity_map_test.rb +++ b/activerecord/test/cases/associations/identity_map_test.rb @@ -128,7 +128,7 @@ class InverseHasManyIdentityMapTest < ActiveRecord::TestCase def test_parent_instance_should_be_shared_with_replaced_via_method_children m = Author.first i = Post.new(:title => 'Industrial Revolution Re-enactment', :body => 'Lorem ipsum') - m.posts.replace([i]) + m.posts = [i] assert_not_nil i.author assert_equal m.name, i.author.name, "Name of man should be the same before changes to parent instance" m.name = 'Bongo' -- cgit v1.2.3 From 6975a41adfa04109e089416a09005425f9562afd Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Fri, 18 Feb 2011 18:50:17 +0000 Subject: Remove test which was broken on 1.8. This test is now irrelevant since singular associations no longer return a proxy object. --- activerecord/test/cases/associations_test.rb | 8 -------- 1 file changed, 8 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb index a1996fcf27..47b8e48582 100644 --- a/activerecord/test/cases/associations_test.rb +++ b/activerecord/test/cases/associations_test.rb @@ -203,14 +203,6 @@ class AssociationProxyTest < ActiveRecord::TestCase assert_equal david.projects, david.projects.reload.reload end end - - if RUBY_VERSION < '1.9' - def test_splat_does_not_invoke_to_a_on_singular_targets - author = posts(:welcome).author - author.reload.target.expects(:to_a).never - [*author] - end - end end class OverridingAssociationsTest < ActiveRecord::TestCase -- cgit v1.2.3 From 3927827dbeae477cb29035107fc3ae49bf5fd1cb Mon Sep 17 00:00:00 2001 From: Emilio Tagua Date: Fri, 18 Feb 2011 16:20:15 -0300 Subject: Don't use skip, just don't run anything, we don't have skip in Ruby 1.8 --- activerecord/test/cases/associations/identity_map_test.rb | 6 ++---- activerecord/test/cases/identity_map_test.rb | 6 ++---- 2 files changed, 4 insertions(+), 8 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/identity_map_test.rb b/activerecord/test/cases/associations/identity_map_test.rb index 73ea13fa7a..9b8635774c 100644 --- a/activerecord/test/cases/associations/identity_map_test.rb +++ b/activerecord/test/cases/associations/identity_map_test.rb @@ -2,13 +2,10 @@ require "cases/helper" require 'models/author' require 'models/post' +if ActiveRecord::IdentityMap.enabled? class InverseHasManyIdentityMapTest < ActiveRecord::TestCase fixtures :authors, :posts - def setup - skip unless ActiveRecord::IdentityMap.enabled? - end - def test_parent_instance_should_be_shared_with_every_child_on_find m = Author.first is = m.posts @@ -137,3 +134,4 @@ class InverseHasManyIdentityMapTest < ActiveRecord::TestCase assert_equal m.name, i.author.name, "Name of man should be the same after changes to replaced-child-owned instance" end end +end diff --git a/activerecord/test/cases/identity_map_test.rb b/activerecord/test/cases/identity_map_test.rb index 6608802c23..d98638ab73 100644 --- a/activerecord/test/cases/identity_map_test.rb +++ b/activerecord/test/cases/identity_map_test.rb @@ -20,15 +20,12 @@ require "models/pirate" require "models/bird" require "models/parrot" +if ActiveRecord::IdentityMap.enabled? class IdentityMapTest < ActiveRecord::TestCase fixtures :accounts, :companies, :developers, :projects, :topics, :developers_projects, :computers, :authors, :author_addresses, :posts, :tags, :taggings, :comments, :subscribers - def setup - skip unless ActiveRecord::IdentityMap.enabled? - end - ############################################################################## # Basic tests checking if IM is functioning properly on basic find operations# ############################################################################## @@ -402,3 +399,4 @@ class IdentityMapTest < ActiveRecord::TestCase # end end +end -- cgit v1.2.3 From ce76cfc61f86931d5acc6db3c2c438cd5ea98255 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sat, 19 Feb 2011 00:42:15 +0100 Subject: fixes a merge conflict --- activerecord/test/cases/autosave_association_test.rb | 10 ---------- 1 file changed, 10 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index 0e93b468c1..ca59b3d6de 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -793,7 +793,6 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase def test_should_destroy_habtm_as_part_of_the_save_transaction_if_they_were_marked_for_destruction 2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") } -<<<<<<< HEAD assert !@pirate.parrots.any? { |parrot| parrot.marked_for_destruction? } @pirate.parrots.each { |parrot| parrot.mark_for_destruction } @@ -809,15 +808,6 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase def test_should_skip_validation_on_habtm_if_marked_for_destruction 2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") } -======= - # Stub the destroy method of the second child to raise an exception - class << before.last - def destroy(*args) - super - raise 'Oh noes!' - end - end ->>>>>>> 220cb107b672d65fdc0488d4ff310ab04b62b463 @pirate.parrots.each { |parrot| parrot.name = '' } assert !@pirate.valid? -- cgit v1.2.3 From 30679bc705c74fcf1d26df275134f7b655a288a8 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 18 Feb 2011 15:51:39 -0800 Subject: AR::AttributeMethods does not need to be included in an AR::Base class. --- .../test/cases/attribute_methods/read_test.rb | 62 ++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 activerecord/test/cases/attribute_methods/read_test.rb (limited to 'activerecord/test') diff --git a/activerecord/test/cases/attribute_methods/read_test.rb b/activerecord/test/cases/attribute_methods/read_test.rb new file mode 100644 index 0000000000..3dc69ea35e --- /dev/null +++ b/activerecord/test/cases/attribute_methods/read_test.rb @@ -0,0 +1,62 @@ +require "cases/helper" + +module ActiveRecord + module AttributeMethods + class ReadTest < ActiveRecord::TestCase + class FakeColumn < Struct.new(:name) + def type_cast_code(var) + var + end + + def type; :integer; end + end + + def setup + @klass = Class.new do + include ActiveRecord::AttributeMethods + include ActiveRecord::AttributeMethods::Read + + def self.column_names + %w{ one two three } + end + + def self.primary_key + end + + def self.columns + column_names.map { FakeColumn.new(name) } + end + + def self.columns_hash + puts caller + Hash[column_names.map { |name| + [name, FakeColumn.new(name)] + }] + end + + def self.serialized_attributes; {}; end + end + end + + def test_define_attribute_methods + instance = @klass.new + + @klass.column_names.each do |name| + assert ! instance.methods.map(&:to_s).include?(name) + end + + @klass.define_attribute_methods + + @klass.column_names.each do |name| + assert(instance.methods.map(&:to_s).include?(name), "#{name} is not defined") + end + end + + def test_attribute_methods_generated? + assert(!@klass.attribute_methods_generated?, 'attribute_methods_generated?') + @klass.define_attribute_methods + assert(@klass.attribute_methods_generated?, 'attribute_methods_generated?') + end + end + end +end -- cgit v1.2.3 From 8657826f416fa2f073c78ba0fab96c33f7b92c39 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 18 Feb 2011 15:53:54 -0800 Subject: oops, no need for puts! --- activerecord/test/cases/attribute_methods/read_test.rb | 1 - 1 file changed, 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/attribute_methods/read_test.rb b/activerecord/test/cases/attribute_methods/read_test.rb index 3dc69ea35e..d0a9028264 100644 --- a/activerecord/test/cases/attribute_methods/read_test.rb +++ b/activerecord/test/cases/attribute_methods/read_test.rb @@ -28,7 +28,6 @@ module ActiveRecord end def self.columns_hash - puts caller Hash[column_names.map { |name| [name, FakeColumn.new(name)] }] -- cgit v1.2.3 From 2a75c190d43dc6ea9d43216d324b7c0f38a1c65d Mon Sep 17 00:00:00 2001 From: Nicholas Rowe Date: Sat, 19 Feb 2011 23:47:12 -0500 Subject: Tpyo: fixing several cases of the the --- activerecord/test/cases/autosave_association_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index 0e93b468c1..0dfdaa3443 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -743,7 +743,7 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase 2.times { |i| @pirate.birds.create!(:name => "birds_#{i}") } before = @pirate.birds.map { |c| c.mark_for_destruction ; c } - # Stub the destroy method of the the second child to raise an exception + # Stub the destroy method of the second child to raise an exception class << before.last def destroy(*args) super -- cgit v1.2.3 From 52f8e4b9dae6137fcd95793dffc26ddff80b623e Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Mon, 21 Feb 2011 01:09:41 +0000 Subject: Use proper objects to do the work to build the associations (adding methods, callbacks etc) rather than calling a whole bunch of methods with rather long names. --- .../test/cases/associations/extension_test.rb | 20 ++++++++++++-------- activerecord/test/cases/autosave_association_test.rb | 8 ++++---- 2 files changed, 16 insertions(+), 12 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/extension_test.rb b/activerecord/test/cases/associations/extension_test.rb index e1f5b16eca..24830a661a 100644 --- a/activerecord/test/cases/associations/extension_test.rb +++ b/activerecord/test/cases/associations/extension_test.rb @@ -29,7 +29,7 @@ class AssociationsExtensionsTest < ActiveRecord::TestCase assert_equal projects(:action_controller), developers(:david).projects_extended_by_name_and_block.find_most_recent assert_equal projects(:active_record), developers(:david).projects_extended_by_name_and_block.find_least_recent end - + def test_extension_with_scopes assert_equal comments(:greetings), posts(:welcome).comments.offset(1).find_most_recent assert_equal comments(:greetings), posts(:welcome).comments.not_again.find_most_recent @@ -52,12 +52,16 @@ class AssociationsExtensionsTest < ActiveRecord::TestCase end def test_extension_name - extension = Proc.new {} - name = :association_name - - assert_equal 'DeveloperAssociationNameAssociationExtension', Developer.send(:create_extension_modules, name, extension, []).first.name - assert_equal 'MyApplication::Business::DeveloperAssociationNameAssociationExtension', MyApplication::Business::Developer.send(:create_extension_modules, name, extension, []).first.name - assert_equal 'MyApplication::Business::DeveloperAssociationNameAssociationExtension', MyApplication::Business::Developer.send(:create_extension_modules, name, extension, []).first.name - assert_equal 'MyApplication::Business::DeveloperAssociationNameAssociationExtension', MyApplication::Business::Developer.send(:create_extension_modules, name, extension, []).first.name + assert_equal 'DeveloperAssociationNameAssociationExtension', extension_name(Developer) + assert_equal 'MyApplication::Business::DeveloperAssociationNameAssociationExtension', extension_name(MyApplication::Business::Developer) + assert_equal 'MyApplication::Business::DeveloperAssociationNameAssociationExtension', extension_name(MyApplication::Business::Developer) end + + private + + def extension_name(model) + builder = ActiveRecord::Associations::Builder::HasMany.new(model, :association_name, {}) { } + builder.send(:wrap_block_extension) + builder.options[:extend].first.name + end end diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index dbc5d71153..b9d9d89220 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -21,19 +21,19 @@ require 'models/eye' class TestAutosaveAssociationsInGeneral < ActiveRecord::TestCase def test_autosave_should_be_a_valid_option_for_has_one - assert base.valid_keys_for_has_one_association.include?(:autosave) + assert ActiveRecord::Associations::Builder::HasOne.valid_options.include?(:autosave) end def test_autosave_should_be_a_valid_option_for_belongs_to - assert base.valid_keys_for_belongs_to_association.include?(:autosave) + assert ActiveRecord::Associations::Builder::BelongsTo.valid_options.include?(:autosave) end def test_autosave_should_be_a_valid_option_for_has_many - assert base.valid_keys_for_has_many_association.include?(:autosave) + assert ActiveRecord::Associations::Builder::HasMany.valid_options.include?(:autosave) end def test_autosave_should_be_a_valid_option_for_has_and_belongs_to_many - assert base.valid_keys_for_has_and_belongs_to_many_association.include?(:autosave) + assert ActiveRecord::Associations::Builder::HasAndBelongsToMany.valid_options.include?(:autosave) end def test_should_not_add_the_same_callbacks_multiple_times_for_has_one -- cgit v1.2.3 From b3fcabb3a529e8ea3d2d6326b2d99aac4222cf06 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 21 Feb 2011 16:11:52 -0800 Subject: adding a test case for custom locking --- activerecord/test/cases/custom_locking_test.rb | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 activerecord/test/cases/custom_locking_test.rb (limited to 'activerecord/test') diff --git a/activerecord/test/cases/custom_locking_test.rb b/activerecord/test/cases/custom_locking_test.rb new file mode 100644 index 0000000000..d63ecdbcc5 --- /dev/null +++ b/activerecord/test/cases/custom_locking_test.rb @@ -0,0 +1,17 @@ +require "cases/helper" +require 'models/person' + +module ActiveRecord + class CustomLockingTest < ActiveRecord::TestCase + fixtures :people + + def test_custom_lock + if current_adapter?(:MysqlAdapter, :Mysql2Adapter) + assert_match 'SHARE MODE', Person.lock('LOCK IN SHARE MODE').to_sql + assert_sql(/LOCK IN SHARE MODE/) do + Person.find(1, :lock => 'LOCK IN SHARE MODE') + end + end + end + end +end -- cgit v1.2.3 From 2cce44fa7c2b5363ab847f01875c6f1b00463b01 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 22 Feb 2011 11:27:12 -0800 Subject: expectations change when using IM. Change oracle tests to reflect that --- activerecord/test/cases/autosave_association_test.rb | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index b9d9d89220..8f55b7ebe6 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -965,7 +965,10 @@ class TestAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase values = [@pirate.reload.catchphrase, @pirate.ship.name, *@pirate.ship.parts.map(&:name)] # Oracle saves empty string as NULL if current_adapter?(:OracleAdapter) - assert_equal [nil, nil, nil, nil], values + expected = ActiveRecord::IdentityMap.enabled? ? + [nil, nil, '', ''] : + [nil, nil, nil, nil] + assert_equal expected, values else assert_equal ['', '', '', ''], values end @@ -1060,7 +1063,8 @@ class TestAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase @ship.save(:validate => false) # Oracle saves empty string as NULL if current_adapter?(:OracleAdapter) - assert_equal [nil, nil], [@ship.reload.name, @ship.pirate.catchphrase] + expected = ActiveRecord::IdentityMap.enabled? ? [nil, ''] : [nil, nil] + assert_equal expected, [@ship.reload.name, @ship.pirate.catchphrase] else assert_equal ['', ''], [@ship.reload.name, @ship.pirate.catchphrase] end -- cgit v1.2.3 From 6ba8caf3ee239fd7010b18ff251cb5c2d52b48c4 Mon Sep 17 00:00:00 2001 From: Kamal Fariz Mahyuddin Date: Wed, 9 Feb 2011 23:37:30 +0800 Subject: Fix observer callbacks firing multiple times on descendant instances --- activerecord/test/cases/lifecycle_test.rb | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/lifecycle_test.rb b/activerecord/test/cases/lifecycle_test.rb index 0558deb71b..a42f5d9c9d 100644 --- a/activerecord/test/cases/lifecycle_test.rb +++ b/activerecord/test/cases/lifecycle_test.rb @@ -7,6 +7,12 @@ require 'models/comment' class SpecialDeveloper < Developer; end +class DeveloperObserver < ActiveRecord::Observer + def before_save(developer) + developer.salary += 1 + end +end + class SalaryChecker < ActiveRecord::Observer observe :special_developer attr_accessor :last_saved @@ -196,4 +202,12 @@ class LifecycleTest < ActiveRecord::TestCase assert_equal developer, SalaryChecker.instance.last_saved end + test "callback observing the ancestor does not fire multiple times on descendent" do + DeveloperObserver.instance # activate + developer = Developer.create! :name => 'Ancestor', :salary => 100000 + assert_equal 100001, developer.salary, 'ancestor callback fired multiple times' + developer = SpecialDeveloper.create! :name => 'Descendent', :salary => 100000 + assert_equal 100001, developer.salary, 'descendent callback fired multiple times' + end + end -- cgit v1.2.3 From 5f1fc0c8ac6e71bfb4d66da2005b1b0694e18446 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Wed, 23 Feb 2011 16:04:01 -0800 Subject: observers leak across tests, so rather than modify the object, we should just count the number of times the observer was called --- activerecord/test/cases/lifecycle_test.rb | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/lifecycle_test.rb b/activerecord/test/cases/lifecycle_test.rb index a42f5d9c9d..6cd8494c9e 100644 --- a/activerecord/test/cases/lifecycle_test.rb +++ b/activerecord/test/cases/lifecycle_test.rb @@ -8,8 +8,12 @@ require 'models/comment' class SpecialDeveloper < Developer; end class DeveloperObserver < ActiveRecord::Observer + def calls + @calls ||= [] + end + def before_save(developer) - developer.salary += 1 + calls << developer end end @@ -202,12 +206,14 @@ class LifecycleTest < ActiveRecord::TestCase assert_equal developer, SalaryChecker.instance.last_saved end - test "callback observing the ancestor does not fire multiple times on descendent" do - DeveloperObserver.instance # activate + def test_observer_is_called_once + observer = DeveloperObserver.instance # activate + observer.calls.clear + developer = Developer.create! :name => 'Ancestor', :salary => 100000 - assert_equal 100001, developer.salary, 'ancestor callback fired multiple times' - developer = SpecialDeveloper.create! :name => 'Descendent', :salary => 100000 - assert_equal 100001, developer.salary, 'descendent callback fired multiple times' + special_developer = SpecialDeveloper.create! :name => 'Descendent', :salary => 100000 + + assert_equal [developer, special_developer], observer.calls end end -- cgit v1.2.3 From 13547c16d97b5f52db11d9f48704bbea20b54a4c Mon Sep 17 00:00:00 2001 From: Eric Allam Date: Tue, 15 Feb 2011 21:48:11 -0500 Subject: fixes: ActiveRecord::Base.scopes includes all scopes defined in all subclasses --- activerecord/test/cases/named_scope_test.rb | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb index d05b0ff947..fb050c3e52 100644 --- a/activerecord/test/cases/named_scope_test.rb +++ b/activerecord/test/cases/named_scope_test.rb @@ -64,6 +64,10 @@ class NamedScopeTest < ActiveRecord::TestCase assert Reply.scopes.include?(:base) assert_equal Reply.find(:all), Reply.base end + + def test_classes_dont_inherit_subclasses_scopes + assert !ActiveRecord::Base.scopes.include?(:base) + end def test_scopes_with_options_limit_finds_to_those_matching_the_criteria_specified assert !Topic.find(:all, :conditions => {:approved => true}).empty? -- cgit v1.2.3 From 54a2bf66019d2694ff53f666765faf5bca927c09 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 25 Feb 2011 15:38:59 -0800 Subject: removing limits and offsets from COUNT queries unless both are specified. [#6268 state:resolved] --- activerecord/test/cases/calculations_test.rb | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index 3121f1615d..991b1ab181 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -109,6 +109,34 @@ class CalculationsTest < ActiveRecord::TestCase assert_equal [2, 6], c.keys.compact end + def test_limit_with_offset_is_kept + queries = assert_sql { Account.limit(1).offset(1).count } + assert_equal 1, queries.length + assert_match(/LIMIT/, queries.first) + assert_match(/OFFSET/, queries.first) + end + + def test_offset_without_limit_removes_offset + queries = assert_sql { Account.offset(1).count } + assert_equal 1, queries.length + assert_no_match(/LIMIT/, queries.first) + assert_no_match(/OFFSET/, queries.first) + end + + def test_limit_without_offset_removes_limit + queries = assert_sql { Account.limit(1).count } + assert_equal 1, queries.length + assert_no_match(/LIMIT/, queries.first) + assert_no_match(/OFFSET/, queries.first) + end + + def test_no_limit_no_offset + queries = assert_sql { Account.count } + assert_equal 1, queries.length + assert_no_match(/LIMIT/, queries.first) + assert_no_match(/OFFSET/, queries.first) + end + def test_should_group_by_summed_field_having_condition c = Account.sum(:credit_limit, :group => :firm_id, :having => 'sum(credit_limit) > 50') -- cgit v1.2.3 From f3e9cbc6955af8f430e75cf5d61e5940f7f46591 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Sat, 26 Feb 2011 16:05:15 -0800 Subject: use an attribute rather than a SQL literal --- activerecord/test/cases/base_test.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 0ad20bb9bc..b62b5003e4 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -134,6 +134,7 @@ class BasicsTest < ActiveRecord::TestCase fakepool = Class.new(Struct.new(:spec)) { def with_connection; yield self; end def connection_pool; self; end + def table_exists?(name); false; end def quote_table_name(*args); raise "lol quote_table_name"; end } -- cgit v1.2.3 From a8dae084c9c1250d7d4a5a70800114b57fbceff6 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 28 Feb 2011 09:15:19 -0800 Subject: skip this on oracle --- activerecord/test/cases/calculations_test.rb | 2 ++ 1 file changed, 2 insertions(+) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index 991b1ab181..caf07a7357 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -110,6 +110,8 @@ class CalculationsTest < ActiveRecord::TestCase end def test_limit_with_offset_is_kept + return if current_adapter?(:OracleAdapter) + queries = assert_sql { Account.limit(1).offset(1).count } assert_equal 1, queries.length assert_match(/LIMIT/, queries.first) -- cgit v1.2.3 From d90b4e2615e8048fdeffc6dffe3246704adee01f Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Wed, 23 Feb 2011 00:17:01 +0000 Subject: Rewrote AssociationPreload. --- activerecord/test/cases/associations/eager_test.rb | 29 +++++++++++----------- .../test/cases/associations/join_model_test.rb | 2 +- activerecord/test/cases/inheritance_test.rb | 2 +- activerecord/test/models/category.rb | 3 ++- 4 files changed, 18 insertions(+), 18 deletions(-) (limited to 'activerecord/test') diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index ca71cd8ed3..26808ae931 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -120,30 +120,29 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_load_associated_records_in_one_query_when_adapter_has_no_limit Post.connection.expects(:in_clause_length).at_least_once.returns(nil) - Post.expects(:i_was_called).with([1,2,3,4,5,6,7]).returns([1]) - associated_records = Post.send(:associated_records, [1,2,3,4,5,6,7]) do |some_ids| - Post.i_was_called(some_ids) + + post = posts(:welcome) + assert_queries(2) do + Post.includes(:comments).where(:id => post.id).to_a end - assert_equal [1], associated_records end def test_load_associated_records_in_several_queries_when_many_ids_passed - Post.connection.expects(:in_clause_length).at_least_once.returns(5) - Post.expects(:i_was_called).with([1,2,3,4,5]).returns([1]) - Post.expects(:i_was_called).with([6,7]).returns([6]) - associated_records = Post.send(:associated_records, [1,2,3,4,5,6,7]) do |some_ids| - Post.i_was_called(some_ids) + Post.connection.expects(:in_clause_length).at_least_once.returns(1) + + post1, post2 = posts(:welcome), posts(:thinking) + assert_queries(3) do + Post.includes(:comments).where(:id => [post1.id, post2.id]).to_a end - assert_equal [1,6], associated_records end def test_load_associated_records_in_one_query_when_a_few_ids_passed - Post.connection.expects(:in_clause_length).at_least_once.returns(5) - Post.expects(:i_was_called).with([1,2,3]).returns([1]) - associated_records = Post.send(:associated_records, [1,2,3]) do |some_ids| - Post.i_was_called(some_ids) + Post.connection.expects(:in_clause_length).at_least_once.returns(3) + + post = posts(:welcome) + assert_queries(2) do + Post.includes(:comments).where(:id => post.id).to_a end - assert_equal [1], associated_records end def test_including_duplicate_objects_from_belongs_to diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb index 6d7f905dc5..19303fef9f 100644 --- a/activerecord/test/cases/associations/join_model_test.rb +++ b/activerecord/test/cases/associations/join_model_test.rb @@ -214,7 +214,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase end def test_has_many_with_piggyback - assert_equal "2", categories(:sti_test).authors.first.post_id.to_s + assert_equal "2", categories(:sti_test).authors_with_select.first.post_id.to_s end def test_include_has_many_through diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb index 680d4ca5dd..b5d8314541 100644 --- a/activerecord/test/cases/inheritance_test.rb +++ b/activerecord/test/cases/inheritance_test.rb @@ -208,7 +208,7 @@ class InheritanceTest < ActiveRecord::TestCase def test_eager_load_belongs_to_primary_key_quoting con = Account.connection - assert_sql(/#{con.quote_table_name('companies')}.#{con.quote_column_name('id')} = 1/) do + assert_sql(/#{con.quote_table_name('companies')}.#{con.quote_column_name('id')} IN \(1\)/) do Account.find(1, :include => :firm) end end diff --git a/activerecord/test/models/category.rb b/activerecord/test/models/category.rb index 06908ea85e..8f37433ec6 100644 --- a/activerecord/test/models/category.rb +++ b/activerecord/test/models/category.rb @@ -22,7 +22,8 @@ class Category < ActiveRecord::Base end has_many :categorizations - has_many :authors, :through => :categorizations, :select => 'authors.*, categorizations.post_id' + has_many :authors, :through => :categorizations + has_many :authors_with_select, :through => :categorizations, :source => :author, :select => 'authors.*, categorizations.post_id' scope :general, :conditions => { :name => 'General' } end -- cgit v1.2.3