aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/test/cases
diff options
context:
space:
mode:
Diffstat (limited to 'activerecord/test/cases')
-rw-r--r--activerecord/test/cases/adapters/mysql/connection_test.rb12
-rw-r--r--activerecord/test/cases/adapters/mysql/enum_test.rb10
-rw-r--r--activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb4
-rw-r--r--activerecord/test/cases/adapters/mysql/reserved_word_test.rb14
-rw-r--r--activerecord/test/cases/adapters/mysql2/connection_test.rb7
-rw-r--r--activerecord/test/cases/adapters/mysql2/enum_test.rb10
-rw-r--r--activerecord/test/cases/adapters/mysql2/reserved_word_test.rb14
-rw-r--r--activerecord/test/cases/adapters/postgresql/active_schema_test.rb4
-rw-r--r--activerecord/test/cases/adapters/postgresql/connection_test.rb85
-rw-r--r--activerecord/test/cases/adapters/postgresql/datatype_test.rb15
-rw-r--r--activerecord/test/cases/adapters/postgresql/timestamp_test.rb65
-rw-r--r--activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb7
-rw-r--r--activerecord/test/cases/associations/association_scope_test.rb15
-rw-r--r--activerecord/test/cases/associations/belongs_to_associations_test.rb24
-rw-r--r--activerecord/test/cases/associations/cascaded_eager_loading_test.rb44
-rw-r--r--activerecord/test/cases/associations/eager_load_nested_include_test.rb4
-rw-r--r--activerecord/test/cases/associations/eager_singularization_test.rb14
-rw-r--r--activerecord/test/cases/associations/eager_test.rb271
-rw-r--r--activerecord/test/cases/associations/extension_test.rb6
-rw-r--r--activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb64
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb183
-rw-r--r--activerecord/test/cases/associations/has_many_through_associations_test.rb15
-rw-r--r--activerecord/test/cases/associations/has_one_associations_test.rb71
-rw-r--r--activerecord/test/cases/associations/has_one_through_associations_test.rb30
-rw-r--r--activerecord/test/cases/associations/inner_join_association_test.rb8
-rw-r--r--activerecord/test/cases/associations/inverse_associations_test.rb24
-rw-r--r--activerecord/test/cases/associations/join_model_test.rb77
-rw-r--r--activerecord/test/cases/associations_test.rb23
-rw-r--r--activerecord/test/cases/attribute_methods/read_test.rb6
-rw-r--r--activerecord/test/cases/attribute_methods_test.rb13
-rw-r--r--activerecord/test/cases/autosave_association_test.rb18
-rw-r--r--activerecord/test/cases/base_test.rb175
-rw-r--r--activerecord/test/cases/calculations_test.rb116
-rw-r--r--activerecord/test/cases/callbacks_test.rb2
-rw-r--r--activerecord/test/cases/column_definition_test.rb6
-rw-r--r--activerecord/test/cases/column_test.rb6
-rw-r--r--activerecord/test/cases/connection_adapters/abstract_adapter_test.rb2
-rw-r--r--activerecord/test/cases/connection_adapters/connection_handler_test.rb5
-rw-r--r--activerecord/test/cases/connection_pool_test.rb104
-rw-r--r--activerecord/test/cases/connection_specification/resolver_test.rb3
-rw-r--r--activerecord/test/cases/counter_cache_test.rb11
-rw-r--r--activerecord/test/cases/custom_locking_test.rb2
-rw-r--r--activerecord/test/cases/defaults_test.rb3
-rw-r--r--activerecord/test/cases/deprecated_dynamic_methods_test.rb35
-rw-r--r--activerecord/test/cases/dirty_test.rb53
-rw-r--r--activerecord/test/cases/explain_subscriber_test.rb10
-rw-r--r--activerecord/test/cases/explain_test.rb16
-rw-r--r--activerecord/test/cases/finder_respond_to_test.rb8
-rw-r--r--activerecord/test/cases/finder_test.rb186
-rw-r--r--activerecord/test/cases/helper.rb6
-rw-r--r--activerecord/test/cases/inclusion_test.rb28
-rw-r--r--activerecord/test/cases/inheritance_test.rb58
-rw-r--r--activerecord/test/cases/json_serialization_test.rb47
-rw-r--r--activerecord/test/cases/locking_test.rb19
-rw-r--r--activerecord/test/cases/log_subscriber_test.rb12
-rw-r--r--activerecord/test/cases/mass_assignment_security_test.rb89
-rw-r--r--activerecord/test/cases/migration/change_schema_test.rb22
-rw-r--r--activerecord/test/cases/migration/change_table_test.rb28
-rw-r--r--activerecord/test/cases/migration/column_attributes_test.rb18
-rw-r--r--activerecord/test/cases/migration/command_recorder_test.rb30
-rw-r--r--activerecord/test/cases/migration/create_join_table_test.rb41
-rw-r--r--activerecord/test/cases/migration/helper.rb27
-rw-r--r--activerecord/test/cases/migration/references_index_test.rb3
-rw-r--r--activerecord/test/cases/migration/references_statements_test.rb111
-rw-r--r--activerecord/test/cases/migration/rename_table_test.rb34
-rw-r--r--activerecord/test/cases/migration_test.rb17
-rw-r--r--activerecord/test/cases/modules_test.rb8
-rw-r--r--activerecord/test/cases/multiple_db_test.rb4
-rw-r--r--activerecord/test/cases/named_scope_test.rb64
-rw-r--r--activerecord/test/cases/nested_attributes_test.rb12
-rw-r--r--activerecord/test/cases/persistence_test.rb167
-rw-r--r--activerecord/test/cases/query_cache_test.rb27
-rw-r--r--activerecord/test/cases/quoting_test.rb8
-rw-r--r--activerecord/test/cases/readonly_test.rb10
-rw-r--r--activerecord/test/cases/reflection_test.rb128
-rw-r--r--activerecord/test/cases/relation_scoping_test.rb36
-rw-r--r--activerecord/test/cases/relation_test.rb11
-rw-r--r--activerecord/test/cases/relations_test.rb255
-rw-r--r--activerecord/test/cases/schema_dumper_test.rb39
-rw-r--r--activerecord/test/cases/serialization_test.rb6
-rw-r--r--activerecord/test/cases/session_store/sql_bypass_test.rb14
-rw-r--r--activerecord/test/cases/store_test.rb17
-rw-r--r--activerecord/test/cases/tasks/database_tasks_test.rb302
-rw-r--r--activerecord/test/cases/tasks/mysql_rake_test.rb268
-rw-r--r--activerecord/test/cases/tasks/postgresql_rake_test.rb226
-rw-r--r--activerecord/test/cases/tasks/sqlite_rake_test.rb191
-rw-r--r--activerecord/test/cases/test_case.rb1
-rw-r--r--activerecord/test/cases/timestamp_test.rb34
-rw-r--r--activerecord/test/cases/transactions_test.rb196
-rw-r--r--activerecord/test/cases/validations/presence_validation_test.rb44
-rw-r--r--activerecord/test/cases/validations/uniqueness_validation_test.rb18
-rw-r--r--activerecord/test/cases/xml_serialization_test.rb73
92 files changed, 3409 insertions, 1240 deletions
diff --git a/activerecord/test/cases/adapters/mysql/connection_test.rb b/activerecord/test/cases/adapters/mysql/connection_test.rb
index 5e1c52c9ba..4bccd2cc59 100644
--- a/activerecord/test/cases/adapters/mysql/connection_test.rb
+++ b/activerecord/test/cases/adapters/mysql/connection_test.rb
@@ -70,11 +70,14 @@ class MysqlConnectionTest < ActiveRecord::TestCase
assert_equal %w{ id data }, result.columns
@connection.exec_query('INSERT INTO ex (id, data) VALUES (1, "foo")')
+
+ # if there are no bind parameters, it will return a string (due to
+ # the libmysql api)
result = @connection.exec_query('SELECT id, data FROM ex')
assert_equal 1, result.rows.length
assert_equal 2, result.columns.length
- assert_equal [[1, 'foo']], result.rows
+ assert_equal [['1', 'foo']], result.rows
end
def test_exec_with_binds
@@ -125,11 +128,12 @@ class MysqlConnectionTest < ActiveRecord::TestCase
assert_equal [["STRICT_ALL_TABLES"]], result.rows
end
- def test_mysql_strict_mode_disabled
+ def test_mysql_strict_mode_disabled_dont_override_global_sql_mode
run_without_connection do |orig_connection|
ActiveRecord::Model.establish_connection(orig_connection.merge({:strict => false}))
- result = ActiveRecord::Model.connection.exec_query "SELECT @@SESSION.sql_mode"
- assert_equal [['']], result.rows
+ global_sql_mode = ActiveRecord::Model.connection.exec_query "SELECT @@GLOBAL.sql_mode"
+ session_sql_mode = ActiveRecord::Model.connection.exec_query "SELECT @@SESSION.sql_mode"
+ assert_equal global_sql_mode.rows, session_sql_mode.rows
end
end
diff --git a/activerecord/test/cases/adapters/mysql/enum_test.rb b/activerecord/test/cases/adapters/mysql/enum_test.rb
new file mode 100644
index 0000000000..40af317ad1
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql/enum_test.rb
@@ -0,0 +1,10 @@
+require "cases/helper"
+
+class MysqlEnumTest < ActiveRecord::TestCase
+ class EnumTest < ActiveRecord::Base
+ end
+
+ def test_enum_limit
+ assert_equal 5, EnumTest.columns.first.limit
+ end
+end
diff --git a/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb b/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb
index 475a292f85..ddfe42b375 100644
--- a/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb
+++ b/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb
@@ -26,7 +26,9 @@ module ActiveRecord
result = @conn.exec_query('SELECT number FROM ex WHERE number = 10')
assert_equal 1, result.rows.length
- assert_equal 10, result.rows.last.last
+ # if there are no bind parameters, it will return a string (due to
+ # the libmysql api)
+ assert_equal '10', result.rows.last.last
end
def test_exec_insert_string
diff --git a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb
index 6faceaf7c0..aff971a955 100644
--- a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb
+++ b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb
@@ -34,11 +34,11 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
'select'=>'id int auto_increment primary key',
'values'=>'id int auto_increment primary key, group_id int',
'distinct'=>'id int auto_increment primary key',
- 'distincts_selects'=>'distinct_id int, select_id int'
+ 'distinct_select'=>'distinct_id int, select_id int'
end
def teardown
- drop_tables_directly ['group', 'select', 'values', 'distinct', 'distincts_selects', 'order']
+ drop_tables_directly ['group', 'select', 'values', 'distinct', 'distinct_select', 'order']
end
# create tables with reserved-word names and columns
@@ -80,7 +80,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
#activerecord model class with reserved-word table name
def test_activerecord_model
- create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
+ create_test_fixtures :select, :distinct, :group, :values, :distinct_select
x = nil
assert_nothing_raised { x = Group.new }
x.order = 'x'
@@ -94,7 +94,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
# has_one association with reserved-word table name
def test_has_one_associations
- create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
+ create_test_fixtures :select, :distinct, :group, :values, :distinct_select
v = nil
assert_nothing_raised { v = Group.find(1).values }
assert_equal 2, v.id
@@ -102,7 +102,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
# belongs_to association with reserved-word table name
def test_belongs_to_associations
- create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
+ create_test_fixtures :select, :distinct, :group, :values, :distinct_select
gs = nil
assert_nothing_raised { gs = Select.find(2).groups }
assert_equal gs.length, 2
@@ -111,7 +111,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
# has_and_belongs_to_many with reserved-word table name
def test_has_and_belongs_to_many
- create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
+ create_test_fixtures :select, :distinct, :group, :values, :distinct_select
s = nil
assert_nothing_raised { s = Distinct.find(1).selects }
assert_equal s.length, 2
@@ -130,7 +130,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
end
def test_associations_work_with_reserved_words
- assert_nothing_raised { Select.scoped(:includes => [:groups]).all }
+ assert_nothing_raised { Select.all.merge!(:includes => [:groups]).to_a }
end
#the following functions were added to DRY test cases
diff --git a/activerecord/test/cases/adapters/mysql2/connection_test.rb b/activerecord/test/cases/adapters/mysql2/connection_test.rb
index 276c499276..c63e4fe5b6 100644
--- a/activerecord/test/cases/adapters/mysql2/connection_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/connection_test.rb
@@ -44,11 +44,12 @@ class MysqlConnectionTest < ActiveRecord::TestCase
assert_equal [["STRICT_ALL_TABLES"]], result.rows
end
- def test_mysql_strict_mode_disabled
+ def test_mysql_strict_mode_disabled_dont_override_global_sql_mode
run_without_connection do |orig_connection|
ActiveRecord::Model.establish_connection(orig_connection.merge({:strict => false}))
- result = ActiveRecord::Model.connection.exec_query "SELECT @@SESSION.sql_mode"
- assert_equal [['']], result.rows
+ global_sql_mode = ActiveRecord::Model.connection.exec_query "SELECT @@GLOBAL.sql_mode"
+ session_sql_mode = ActiveRecord::Model.connection.exec_query "SELECT @@SESSION.sql_mode"
+ assert_equal global_sql_mode.rows, session_sql_mode.rows
end
end
diff --git a/activerecord/test/cases/adapters/mysql2/enum_test.rb b/activerecord/test/cases/adapters/mysql2/enum_test.rb
new file mode 100644
index 0000000000..f3a05e48ad
--- /dev/null
+++ b/activerecord/test/cases/adapters/mysql2/enum_test.rb
@@ -0,0 +1,10 @@
+require "cases/helper"
+
+class Mysql2EnumTest < ActiveRecord::TestCase
+ class EnumTest < ActiveRecord::Base
+ end
+
+ def test_enum_limit
+ assert_equal 5, EnumTest.columns.first.limit
+ end
+end
diff --git a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb
index 32d4282623..9fd07f014e 100644
--- a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb
+++ b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb
@@ -34,11 +34,11 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
'select'=>'id int auto_increment primary key',
'values'=>'id int auto_increment primary key, group_id int',
'distinct'=>'id int auto_increment primary key',
- 'distincts_selects'=>'distinct_id int, select_id int'
+ 'distinct_select'=>'distinct_id int, select_id int'
end
def teardown
- drop_tables_directly ['group', 'select', 'values', 'distinct', 'distincts_selects', 'order']
+ drop_tables_directly ['group', 'select', 'values', 'distinct', 'distinct_select', 'order']
end
# create tables with reserved-word names and columns
@@ -80,7 +80,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
#activerecord model class with reserved-word table name
def test_activerecord_model
- create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
+ create_test_fixtures :select, :distinct, :group, :values, :distinct_select
x = nil
assert_nothing_raised { x = Group.new }
x.order = 'x'
@@ -94,7 +94,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
# has_one association with reserved-word table name
def test_has_one_associations
- create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
+ create_test_fixtures :select, :distinct, :group, :values, :distinct_select
v = nil
assert_nothing_raised { v = Group.find(1).values }
assert_equal 2, v.id
@@ -102,7 +102,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
# belongs_to association with reserved-word table name
def test_belongs_to_associations
- create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
+ create_test_fixtures :select, :distinct, :group, :values, :distinct_select
gs = nil
assert_nothing_raised { gs = Select.find(2).groups }
assert_equal gs.length, 2
@@ -111,7 +111,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
# has_and_belongs_to_many with reserved-word table name
def test_has_and_belongs_to_many
- create_test_fixtures :select, :distinct, :group, :values, :distincts_selects
+ create_test_fixtures :select, :distinct, :group, :values, :distinct_select
s = nil
assert_nothing_raised { s = Distinct.find(1).selects }
assert_equal s.length, 2
@@ -130,7 +130,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase
end
def test_associations_work_with_reserved_words
- assert_nothing_raised { Select.scoped(:includes => [:groups]).all }
+ assert_nothing_raised { Select.all.merge!(:includes => [:groups]).to_a }
end
#the following functions were added to DRY test cases
diff --git a/activerecord/test/cases/adapters/postgresql/active_schema_test.rb b/activerecord/test/cases/adapters/postgresql/active_schema_test.rb
index 447d729e52..113c27b194 100644
--- a/activerecord/test/cases/adapters/postgresql/active_schema_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/active_schema_test.rb
@@ -21,6 +21,10 @@ class PostgresqlActiveSchemaTest < ActiveRecord::TestCase
assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'latin1'), create_database(:aimonetti, :encoding => :latin1)
end
+ def test_create_database_with_collation_and_ctype
+ assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'UTF8' LC_COLLATE = 'ja_JP.UTF8' LC_CTYPE = 'ja_JP.UTF8'), create_database(:aimonetti, :encoding => :"UTF8", :collation => :"ja_JP.UTF8", :ctype => :"ja_JP.UTF8")
+ end
+
def test_add_index
# add_index calls index_name_exists? which can't work since execute is stubbed
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.send(:define_method, :index_name_exists?) do |*|
diff --git a/activerecord/test/cases/adapters/postgresql/connection_test.rb b/activerecord/test/cases/adapters/postgresql/connection_test.rb
index adb2cef010..1ff307c735 100644
--- a/activerecord/test/cases/adapters/postgresql/connection_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/connection_test.rb
@@ -21,6 +21,18 @@ module ActiveRecord
assert_not_nil @connection.encoding
end
+ def test_collation
+ assert_not_nil @connection.collation
+ end
+
+ def test_ctype
+ assert_not_nil @connection.ctype
+ end
+
+ def test_default_client_min_messages
+ assert_equal "warning", @connection.client_min_messages
+ end
+
# Ensure, we can set connection params using the example of Generic
# Query Optimizer (geqo). It is 'on' per default.
def test_connection_options
@@ -69,5 +81,78 @@ module ActiveRecord
assert_equal 'SCHEMA', @connection.logged[0][1]
end
+ def test_reconnection_after_simulated_disconnection_with_verify
+ assert @connection.active?
+ original_connection_pid = @connection.query('select pg_backend_pid()')
+
+ # Fail with bad connection on next query attempt.
+ raw_connection = @connection.raw_connection
+ raw_connection_class = class << raw_connection ; self ; end
+ raw_connection_class.class_eval <<-CODE, __FILE__, __LINE__ + 1
+ def query_fake(*args)
+ if !( @called ||= false )
+ self.stubs(:status).returns(PGconn::CONNECTION_BAD)
+ @called = true
+ raise PGError
+ else
+ self.unstub(:status)
+ query_unfake(*args)
+ end
+ end
+
+ alias query_unfake query
+ alias query query_fake
+ CODE
+
+ begin
+ @connection.verify!
+ new_connection_pid = @connection.query('select pg_backend_pid()')
+ ensure
+ raw_connection_class.class_eval <<-CODE
+ alias query query_unfake
+ undef query_fake
+ CODE
+ end
+
+ assert_not_equal original_connection_pid, new_connection_pid, "Should have a new underlying connection pid"
+ end
+
+ # Must have with_manual_interventions set to true for this
+ # test to run.
+ # When prompted, restart the PostgreSQL server with the
+ # "-m fast" option or kill the individual connection assuming
+ # you know the incantation to do that.
+ # To restart PostgreSQL 9.1 on OS X, installed via MacPorts, ...
+ # sudo su postgres -c "pg_ctl restart -D /opt/local/var/db/postgresql91/defaultdb/ -m fast"
+ def test_reconnection_after_actual_disconnection_with_verify
+ skip "with_manual_interventions is false in configuration" unless ARTest.config['with_manual_interventions']
+
+ original_connection_pid = @connection.query('select pg_backend_pid()')
+
+ # Sanity check.
+ assert @connection.active?
+
+ puts 'Kill the connection now (e.g. by restarting the PostgreSQL ' +
+ 'server with the "-m fast" option) and then press enter.'
+ $stdin.gets
+
+ @connection.verify!
+
+ assert @connection.active?
+
+ # If we get no exception here, then either we re-connected successfully, or
+ # we never actually got disconnected.
+ new_connection_pid = @connection.query('select pg_backend_pid()')
+
+ assert_not_equal original_connection_pid, new_connection_pid,
+ "umm -- looks like you didn't break the connection, because we're still " +
+ "successfully querying with the same connection pid."
+
+ # Repair all fixture connections so other tests won't break.
+ @fixture_connections.each do |c|
+ c.verify!
+ end
+ end
+
end
end
diff --git a/activerecord/test/cases/adapters/postgresql/datatype_test.rb b/activerecord/test/cases/adapters/postgresql/datatype_test.rb
index 34660577da..a4d9286d52 100644
--- a/activerecord/test/cases/adapters/postgresql/datatype_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/datatype_test.rb
@@ -27,6 +27,9 @@ end
class PostgresqlTimestampWithZone < ActiveRecord::Base
end
+class PostgresqlUUID < ActiveRecord::Base
+end
+
class PostgresqlDataTypeTest < ActiveRecord::TestCase
self.use_transactional_fixtures = false
@@ -61,6 +64,9 @@ class PostgresqlDataTypeTest < ActiveRecord::TestCase
@first_oid = PostgresqlOid.find(1)
@connection.execute("INSERT INTO postgresql_timestamp_with_zones (time) VALUES ('2010-01-01 10:00:00-1')")
+
+ @connection.execute("INSERT INTO postgresql_uuids (guid, compact_guid) VALUES('d96c3da0-96c1-012f-1316-64ce8f32c6d8', 'f06c715096c1012f131764ce8f32c6d8')")
+ @first_uuid = PostgresqlUUID.find(1)
end
def test_data_type_of_array_types
@@ -100,6 +106,10 @@ class PostgresqlDataTypeTest < ActiveRecord::TestCase
assert_equal :integer, @first_oid.column_for_attribute(:obj_id).type
end
+ def test_data_type_of_uuid_types
+ assert_equal :uuid, @first_uuid.column_for_attribute(:guid).type
+ end
+
def test_array_values
assert_equal '{35000,21000,18000,17000}', @first_array.commission_by_quarter
assert_equal '{foo,bar,baz}', @first_array.nicknames
@@ -143,6 +153,11 @@ class PostgresqlDataTypeTest < ActiveRecord::TestCase
assert_equal '01:23:45:67:89:0a', @first_network_address.mac_address
end
+ def test_uuid_values
+ assert_equal 'd96c3da0-96c1-012f-1316-64ce8f32c6d8', @first_uuid.guid
+ assert_equal 'f06c7150-96c1-012f-1317-64ce8f32c6d8', @first_uuid.compact_guid
+ end
+
def test_bit_string_values
assert_equal '00010101', @first_bit_string.bit_string
assert_equal '00010101', @first_bit_string.bit_string_varying
diff --git a/activerecord/test/cases/adapters/postgresql/timestamp_test.rb b/activerecord/test/cases/adapters/postgresql/timestamp_test.rb
index 337f43c421..26507ad654 100644
--- a/activerecord/test/cases/adapters/postgresql/timestamp_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/timestamp_test.rb
@@ -27,4 +27,69 @@ class TimestampTest < ActiveRecord::TestCase
d = Developer.create!(:name => 'aaron', :updated_at => -1.0 / 0.0)
assert_equal(-1.0 / 0.0, d.updated_at)
end
+
+ def test_default_datetime_precision
+ ActiveRecord::Base.connection.create_table(:foos)
+ ActiveRecord::Base.connection.add_column :foos, :created_at, :datetime
+ ActiveRecord::Base.connection.add_column :foos, :updated_at, :datetime
+ assert_nil activerecord_column_option('foos', 'created_at', 'precision')
+ end
+
+ def test_timestamp_data_type_with_precision
+ ActiveRecord::Base.connection.create_table(:foos)
+ ActiveRecord::Base.connection.add_column :foos, :created_at, :datetime, :precision => 0
+ ActiveRecord::Base.connection.add_column :foos, :updated_at, :datetime, :precision => 5
+ assert_equal 0, activerecord_column_option('foos', 'created_at', 'precision')
+ assert_equal 5, activerecord_column_option('foos', 'updated_at', 'precision')
+ end
+
+ def test_timestamps_helper_with_custom_precision
+ ActiveRecord::Base.connection.create_table(:foos) do |t|
+ t.timestamps :precision => 4
+ end
+ assert_equal 4, activerecord_column_option('foos', 'created_at', 'precision')
+ assert_equal 4, activerecord_column_option('foos', 'updated_at', 'precision')
+ end
+
+ def test_passing_precision_to_timestamp_does_not_set_limit
+ ActiveRecord::Base.connection.create_table(:foos) do |t|
+ t.timestamps :precision => 4
+ end
+ assert_nil activerecord_column_option("foos", "created_at", "limit")
+ assert_nil activerecord_column_option("foos", "updated_at", "limit")
+ end
+
+ def test_invalid_timestamp_precision_raises_error
+ assert_raises ActiveRecord::ActiveRecordError do
+ ActiveRecord::Base.connection.create_table(:foos) do |t|
+ t.timestamps :precision => 7
+ end
+ end
+ end
+
+ def test_postgres_agrees_with_activerecord_about_precision
+ ActiveRecord::Base.connection.create_table(:foos) do |t|
+ t.timestamps :precision => 4
+ end
+ assert_equal '4', pg_datetime_precision('foos', 'created_at')
+ assert_equal '4', pg_datetime_precision('foos', 'updated_at')
+ end
+
+ private
+
+ def pg_datetime_precision(table_name, column_name)
+ results = ActiveRecord::Base.connection.execute("SELECT column_name, datetime_precision FROM information_schema.columns WHERE table_name ='#{table_name}'")
+ result = results.find do |result_hash|
+ result_hash["column_name"] == column_name
+ end
+ result && result["datetime_precision"]
+ end
+
+ def activerecord_column_option(tablename, column_name, option)
+ result = ActiveRecord::Base.connection.columns(tablename).find do |column|
+ column.name == column_name
+ end
+ result && result.send(option)
+ end
+
end
diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
index 5e947799cc..4e26c5dda1 100644
--- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
+++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
@@ -24,7 +24,7 @@ module ActiveRecord
@conn.extend(LogIntercepter)
@conn.intercepted = true
end
-
+
def teardown
@conn.intercepted = false
@conn.logged = []
@@ -43,11 +43,6 @@ module ActiveRecord
assert(!result.rows.first.include?("blob"), "should not store blobs")
end
- def test_time_column
- owner = Owner.create!(:eats_at => Time.utc(1995,1,1,6,0))
- assert_match(/1995-01-01/, owner.reload.eats_at.to_s)
- end
-
def test_exec_insert
column = @conn.columns('items').find { |col| col.name == 'number' }
vals = [[column, 10]]
diff --git a/activerecord/test/cases/associations/association_scope_test.rb b/activerecord/test/cases/associations/association_scope_test.rb
new file mode 100644
index 0000000000..d38648202e
--- /dev/null
+++ b/activerecord/test/cases/associations/association_scope_test.rb
@@ -0,0 +1,15 @@
+require 'cases/helper'
+require 'models/post'
+require 'models/author'
+
+module ActiveRecord
+ module Associations
+ class AssociationScopeTest < ActiveRecord::TestCase
+ test 'does not duplicate conditions' do
+ association_scope = AssociationScope.new(Author.new.association(:welcome_posts))
+ wheres = association_scope.scope.where_values.map(&:right)
+ assert_equal wheres.uniq, wheres
+ 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 2c7a240915..5f7825783b 100644
--- a/activerecord/test/cases/associations/belongs_to_associations_test.rb
+++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -73,14 +73,14 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
def test_eager_loading_with_primary_key
Firm.create("name" => "Apple")
Client.create("name" => "Citibank", :firm_name => "Apple")
- citibank_result = Client.scoped(:where => {:name => "Citibank"}, :includes => :firm_with_primary_key).first
+ citibank_result = Client.all.merge!(:where => {:name => "Citibank"}, :includes => :firm_with_primary_key).first
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.scoped(:where => {:name => "Citibank"}, :includes => :firm_with_primary_key_symbols).first
+ citibank_result = Client.all.merge!(:where => {:name => "Citibank"}, :includes => :firm_with_primary_key_symbols).first
assert citibank_result.association_cache.key?(:firm_with_primary_key_symbols)
end
@@ -181,8 +181,8 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
end
def test_with_select
- assert_equal Company.find(2).firm_with_select.attributes.size, 1
- assert_equal Company.scoped(:includes => :firm_with_select ).find(2).firm_with_select.attributes.size, 1
+ assert_equal 1, Company.find(2).firm_with_select.attributes.size
+ assert_equal 1, Company.all.merge!(:includes => :firm_with_select ).find(2).firm_with_select.attributes.size
end
def test_belongs_to_counter
@@ -298,12 +298,12 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_equal 1, Topic.find(topic.id)[:replies_count]
end
- def test_belongs_to_counter_when_update_column
+ def test_belongs_to_counter_when_update_columns
topic = Topic.create!(:title => "37s")
topic.replies.create!(:title => "re: 37s", :content => "rails")
assert_equal 1, Topic.find(topic.id)[:replies_count]
- topic.update_column(:content, "rails is wonderfull")
+ topic.update_columns(content: "rails is wonderfull")
assert_equal 1, Topic.find(topic.id)[:replies_count]
end
@@ -334,7 +334,7 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
def test_new_record_with_foreign_key_but_no_object
c = Client.new("firm_id" => 1)
# sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
- assert_equal Firm.scoped(:order => "id").first, c.firm_with_basic_id
+ assert_equal Firm.all.merge!(:order => "id").first, c.firm_with_basic_id
end
def test_setting_foreign_key_after_nil_target_loaded
@@ -396,7 +396,7 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
def test_association_assignment_sticks
post = Post.first
- author1, author2 = Author.scoped(:limit => 2).all
+ author1, author2 = Author.all.merge!(:limit => 2).to_a
assert_not_nil author1
assert_not_nil author2
@@ -498,14 +498,14 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
assert_nothing_raised do
Account.find(@account.id).save!
- Account.scoped(:includes => :firm).find(@account.id).save!
+ Account.all.merge!(:includes => :firm).find(@account.id).save!
end
@account.firm.delete
assert_nothing_raised do
Account.find(@account.id).save!
- Account.scoped(:includes => :firm).find(@account.id).save!
+ Account.all.merge!(:includes => :firm).find(@account.id).save!
end
end
@@ -524,13 +524,13 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
def test_invalid_belongs_to_dependent_option_nullify_raises_exception
assert_raise ArgumentError do
- Author.belongs_to :special_author_address, :dependent => :nullify
+ Class.new(Author).belongs_to :special_author_address, :dependent => :nullify
end
end
def test_invalid_belongs_to_dependent_option_restrict_raises_exception
assert_raise ArgumentError do
- Author.belongs_to :special_author_address, :dependent => :restrict
+ Class.new(Author).belongs_to :special_author_address, :dependent => :restrict
end
end
diff --git a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb
index 01f7f18397..80bca7f63e 100644
--- a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb
+++ b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb
@@ -16,7 +16,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
:categorizations, :people, :categories, :edges, :vertices
def test_eager_association_loading_with_cascaded_two_levels
- authors = Author.scoped(:includes=>{:posts=>:comments}, :order=>"authors.id").all
+ authors = Author.all.merge!(:includes=>{:posts=>:comments}, :order=>"authors.id").to_a
assert_equal 3, authors.size
assert_equal 5, authors[0].posts.size
assert_equal 3, authors[1].posts.size
@@ -24,7 +24,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_cascaded_two_levels_and_one_level
- authors = Author.scoped(:includes=>[{:posts=>:comments}, :categorizations], :order=>"authors.id").all
+ authors = Author.all.merge!(:includes=>[{:posts=>:comments}, :categorizations], :order=>"authors.id").to_a
assert_equal 3, authors.size
assert_equal 5, authors[0].posts.size
assert_equal 3, authors[1].posts.size
@@ -35,16 +35,16 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
def test_eager_association_loading_with_hmt_does_not_table_name_collide_when_joining_associations
assert_nothing_raised do
- Author.joins(:posts).eager_load(:comments).where(:posts => {:taggings_count => 1}).all
+ Author.joins(:posts).eager_load(:comments).where(:posts => {:taggings_count => 1}).to_a
end
- authors = Author.joins(:posts).eager_load(:comments).where(:posts => {:taggings_count => 1}).all
+ authors = Author.joins(:posts).eager_load(:comments).where(:posts => {:taggings_count => 1}).to_a
assert_equal 1, assert_no_queries { authors.size }
assert_equal 10, assert_no_queries { authors[0].comments.size }
end
def test_eager_association_loading_grafts_stashed_associations_to_correct_parent
assert_nothing_raised do
- Person.eager_load(:primary_contact => :primary_contact).where('primary_contacts_people_2.first_name = ?', 'Susan').order('people.id').all
+ Person.eager_load(:primary_contact => :primary_contact).where('primary_contacts_people_2.first_name = ?', 'Susan').order('people.id').to_a
end
assert_equal people(:michael), Person.eager_load(:primary_contact => :primary_contact).where('primary_contacts_people_2.first_name = ?', 'Susan').order('people.id').first
end
@@ -54,9 +54,9 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
assert_nothing_raised do
assert_equal 4, categories.count
- assert_equal 4, categories.all.count
+ assert_equal 4, categories.to_a.count
assert_equal 3, categories.count(:distinct => true)
- assert_equal 3, categories.all.uniq.size # Must uniq since instantiating with inner joins will get dupes
+ assert_equal 3, categories.to_a.uniq.size # Must uniq since instantiating with inner joins will get dupes
end
end
@@ -64,7 +64,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
categories = Category.includes(:categorizations).includes(:categorizations => :author).where("categorizations.id is not null").references(:categorizations)
assert_nothing_raised do
assert_equal 3, categories.count
- assert_equal 3, categories.all.size
+ assert_equal 3, categories.to_a.size
end
end
@@ -72,7 +72,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
categories = Category.includes(:categorizations => :author).includes(:categorizations => :post).where("posts.id is not null").references(:posts)
assert_nothing_raised do
assert_equal 3, categories.count
- assert_equal 3, categories.all.size
+ assert_equal 3, categories.to_a.size
end
end
@@ -80,11 +80,11 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
authors = Author.joins(:special_posts).includes([:posts, :categorizations])
assert_nothing_raised { authors.count }
- assert_queries(3) { authors.all }
+ assert_queries(3) { authors.to_a }
end
def test_eager_association_loading_with_cascaded_two_levels_with_two_has_many_associations
- authors = Author.scoped(:includes=>{:posts=>[:comments, :categorizations]}, :order=>"authors.id").all
+ authors = Author.all.merge!(:includes=>{:posts=>[:comments, :categorizations]}, :order=>"authors.id").to_a
assert_equal 3, authors.size
assert_equal 5, authors[0].posts.size
assert_equal 3, authors[1].posts.size
@@ -92,7 +92,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_cascaded_two_levels_and_self_table_reference
- authors = Author.scoped(:includes=>{:posts=>[:comments, :author]}, :order=>"authors.id").all
+ authors = Author.all.merge!(:includes=>{:posts=>[:comments, :author]}, :order=>"authors.id").to_a
assert_equal 3, authors.size
assert_equal 5, authors[0].posts.size
assert_equal authors(:david).name, authors[0].name
@@ -100,13 +100,13 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_cascaded_two_levels_with_condition
- authors = Author.scoped(:includes=>{:posts=>:comments}, :where=>"authors.id=1", :order=>"authors.id").all
+ authors = Author.all.merge!(:includes=>{:posts=>:comments}, :where=>"authors.id=1", :order=>"authors.id").to_a
assert_equal 1, authors.size
assert_equal 5, authors[0].posts.size
end
def test_eager_association_loading_with_cascaded_three_levels_by_ping_pong
- firms = Firm.scoped(:includes=>{:account=>{:firm=>:account}}, :order=>"companies.id").all
+ firms = Firm.all.merge!(:includes=>{:account=>{:firm=>:account}}, :order=>"companies.id").to_a
assert_equal 2, firms.size
assert_equal firms.first.account, firms.first.account.firm.account
assert_equal companies(:first_firm).account, assert_no_queries { firms.first.account.firm.account }
@@ -114,7 +114,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_has_many_sti
- topics = Topic.scoped(:includes => :replies, :order => 'topics.id').all
+ topics = Topic.all.merge!(:includes => :replies, :order => 'topics.id').to_a
first, second, = topics(:first).replies.size, topics(:second).replies.size
assert_no_queries do
assert_equal first, topics[0].replies.size
@@ -127,7 +127,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
silly.parent_id = 1
assert silly.save
- topics = Topic.scoped(:includes => :replies, :order => ['topics.id', 'replies_topics.id']).all
+ topics = Topic.all.merge!(:includes => :replies, :order => ['topics.id', 'replies_topics.id']).to_a
assert_no_queries do
assert_equal 2, topics[0].replies.size
assert_equal 0, topics[1].replies.size
@@ -135,14 +135,14 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_belongs_to_sti
- replies = Reply.scoped(:includes => :topic, :order => 'topics.id').all
+ replies = Reply.all.merge!(:includes => :topic, :order => 'topics.id').to_a
assert replies.include?(topics(:second))
assert !replies.include?(topics(:first))
assert_equal topics(:first), assert_no_queries { replies.first.topic }
end
def test_eager_association_loading_with_multiple_stis_and_order
- author = Author.scoped(:includes => { :posts => [ :special_comments , :very_special_comment ] }, :order => ['authors.name', 'comments.body', 'very_special_comments_posts.body'], :where => 'posts.id = 4').first
+ author = Author.all.merge!(:includes => { :posts => [ :special_comments , :very_special_comment ] }, :order => ['authors.name', 'comments.body', 'very_special_comments_posts.body'], :where => 'posts.id = 4').first
assert_equal authors(:david), author
assert_no_queries do
author.posts.first.special_comments
@@ -151,7 +151,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_eager_association_loading_of_stis_with_multiple_references
- authors = Author.scoped(:includes => { :posts => { :special_comments => { :post => [ :special_comments, :very_special_comment ] } } }, :order => 'comments.body, very_special_comments_posts.body', :where => 'posts.id = 4').all
+ authors = Author.all.merge!(:includes => { :posts => { :special_comments => { :post => [ :special_comments, :very_special_comment ] } } }, :order => 'comments.body, very_special_comments_posts.body', :where => 'posts.id = 4').to_a
assert_equal [authors(:david)], authors
assert_no_queries do
authors.first.posts.first.special_comments.first.post.special_comments
@@ -160,7 +160,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_eager_association_loading_where_first_level_returns_nil
- authors = Author.scoped(:includes => {:post_about_thinking => :comments}, :order => 'authors.id DESC').all
+ authors = Author.all.merge!(:includes => {:post_about_thinking => :comments}, :order => 'authors.id DESC').to_a
assert_equal [authors(:bob), authors(:mary), authors(:david)], authors
assert_no_queries do
authors[2].post_about_thinking.comments.first
@@ -168,12 +168,12 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_recursive_cascading_four_levels_has_many_through
- source = Vertex.scoped(:includes=>{:sinks=>{:sinks=>{:sinks=>:sinks}}}, :order => 'vertices.id').first
+ source = Vertex.all.merge!(:includes=>{:sinks=>{:sinks=>{:sinks=>:sinks}}}, :order => 'vertices.id').first
assert_equal vertices(:vertex_4), assert_no_queries { source.sinks.first.sinks.first.sinks.first }
end
def test_eager_association_loading_with_recursive_cascading_four_levels_has_and_belongs_to_many
- sink = Vertex.scoped(:includes=>{:sources=>{:sources=>{:sources=>:sources}}}, :order => 'vertices.id DESC').first
+ sink = Vertex.all.merge!(:includes=>{:sources=>{:sources=>{:sources=>:sources}}}, :order => 'vertices.id DESC').first
assert_equal vertices(:vertex_1), assert_no_queries { sink.sources.first.sources.first.sources.first.sources.first }
end
end
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 bb0d6bc70b..5ff117eaa0 100644
--- a/activerecord/test/cases/associations/eager_load_nested_include_test.rb
+++ b/activerecord/test/cases/associations/eager_load_nested_include_test.rb
@@ -92,7 +92,7 @@ class EagerLoadPolyAssocsTest < ActiveRecord::TestCase
end
def test_include_query
- res = ShapeExpression.scoped(:includes => [ :shape, { :paint => :non_poly } ]).all
+ res = ShapeExpression.all.merge!(:includes => [ :shape, { :paint => :non_poly } ]).to_a
assert_equal NUM_SHAPE_EXPRESSIONS, res.size
assert_queries(0) do
res.each do |se|
@@ -122,7 +122,7 @@ class EagerLoadNestedIncludeWithMissingDataTest < ActiveRecord::TestCase
assert_nothing_raised do
# @davey_mcdave doesn't have any author_favorites
includes = {:posts => :comments, :categorizations => :category, :author_favorites => :favorite_author }
- Author.scoped(:includes => includes, :where => {:authors => {:name => @davey_mcdave.name}}, :order => 'categories.name').to_a
+ Author.all.merge!(:includes => includes, :where => {:authors => {:name => @davey_mcdave.name}}, :order => 'categories.name').to_a
end
end
end
diff --git a/activerecord/test/cases/associations/eager_singularization_test.rb b/activerecord/test/cases/associations/eager_singularization_test.rb
index 5805e71249..634f6b63ba 100644
--- a/activerecord/test/cases/associations/eager_singularization_test.rb
+++ b/activerecord/test/cases/associations/eager_singularization_test.rb
@@ -103,43 +103,43 @@ class EagerSingularizationTest < ActiveRecord::TestCase
def test_eager_no_extra_singularization_belongs_to
return unless @have_tables
assert_nothing_raised do
- Virus.scoped(:includes => :octopus).all
+ Virus.all.merge!(:includes => :octopus).to_a
end
end
def test_eager_no_extra_singularization_has_one
return unless @have_tables
assert_nothing_raised do
- Octopus.scoped(:includes => :virus).all
+ Octopus.all.merge!(:includes => :virus).to_a
end
end
def test_eager_no_extra_singularization_has_many
return unless @have_tables
assert_nothing_raised do
- Bus.scoped(:includes => :passes).all
+ Bus.all.merge!(:includes => :passes).to_a
end
end
def test_eager_no_extra_singularization_has_and_belongs_to_many
return unless @have_tables
assert_nothing_raised do
- Crisis.scoped(:includes => :messes).all
- Mess.scoped(:includes => :crises).all
+ Crisis.all.merge!(:includes => :messes).to_a
+ Mess.all.merge!(:includes => :crises).to_a
end
end
def test_eager_no_extra_singularization_has_many_through_belongs_to
return unless @have_tables
assert_nothing_raised do
- Crisis.scoped(:includes => :successes).all
+ Crisis.all.merge!(:includes => :successes).to_a
end
end
def test_eager_no_extra_singularization_has_many_through_has_many
return unless @have_tables
assert_nothing_raised do
- Crisis.scoped(:includes => :compresses).all
+ Crisis.all.merge!(:includes => :compresses).to_a
end
end
end
diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb
index 08467900f9..da4eeb3844 100644
--- a/activerecord/test/cases/associations/eager_test.rb
+++ b/activerecord/test/cases/associations/eager_test.rb
@@ -29,48 +29,43 @@ class EagerAssociationTest < ActiveRecord::TestCase
:owners, :pets, :author_favorites, :jobs, :references, :subscribers, :subscriptions, :books,
:developers, :projects, :developers_projects, :members, :memberships, :clubs, :sponsors
- 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.scoped(:includes => :favourite_club).find(members(:some_other_guy).id)
+ member = Member.all.merge!(:includes => :favourite_club).find(members(:some_other_guy).id)
assert_nil member.favourite_club
end
def test_loading_with_one_association
- posts = Post.scoped(:includes => :comments).all
+ posts = Post.all.merge!(:includes => :comments).to_a
post = posts.find { |p| p.id == 1 }
assert_equal 2, post.comments.size
assert post.comments.include?(comments(:greetings))
- post = Post.scoped(:includes => :comments, :where => "posts.title = 'Welcome to the weblog'").first
+ post = Post.all.merge!(:includes => :comments, :where => "posts.title = 'Welcome to the weblog'").first
assert_equal 2, post.comments.size
assert post.comments.include?(comments(:greetings))
- posts = Post.scoped(:includes => :last_comment).all
+ posts = Post.all.merge!(:includes => :last_comment).to_a
post = posts.find { |p| p.id == 1 }
assert_equal Post.find(1).last_comment, post.last_comment
end
def test_loading_with_one_association_with_non_preload
- posts = Post.scoped(:includes => :last_comment, :order => 'comments.id DESC').all
+ posts = Post.all.merge!(:includes => :last_comment, :order => 'comments.id DESC').to_a
post = posts.find { |p| p.id == 1 }
assert_equal Post.find(1).last_comment, post.last_comment
end
def test_loading_conditions_with_or
- posts = authors(:david).posts.references(:comments).scoped(
+ posts = authors(:david).posts.references(:comments).merge(
:includes => :comments,
:where => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE} = 'SpecialComment'"
- ).all
+ ).to_a
assert_nil posts.detect { |p| p.author_id != authors(:david).id },
"expected to find only david's posts"
end
def test_with_ordering
- list = Post.scoped(:includes => :comments, :order => "posts.id DESC").all
+ list = Post.all.merge!(:includes => :comments, :order => "posts.id DESC").to_a
[:other_by_mary, :other_by_bob, :misc_by_mary, :misc_by_bob, :eager_other,
:sti_habtm, :sti_post_and_comments, :sti_comments, :authorless, :thinking, :welcome
].each_with_index do |post, index|
@@ -84,14 +79,14 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_loading_with_multiple_associations
- posts = Post.scoped(:includes => [ :comments, :author, :categories ], :order => "posts.id").all
+ posts = Post.all.merge!(:includes => [ :comments, :author, :categories ], :order => "posts.id").to_a
assert_equal 2, posts.first.comments.size
assert_equal 2, posts.first.categories.size
assert posts.first.comments.include?(comments(:greetings))
end
def test_duplicate_middle_objects
- comments = Comment.scoped(:where => 'post_id = 1', :includes => [:post => :author]).all
+ comments = Comment.all.merge!(:where => 'post_id = 1', :includes => [:post => :author]).to_a
assert_no_queries do
comments.each {|comment| comment.post.author.name}
end
@@ -99,25 +94,25 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_preloading_has_many_in_multiple_queries_with_more_ids_than_database_can_handle
Post.connection.expects(:in_clause_length).at_least_once.returns(5)
- posts = Post.scoped(:includes=>:comments).all
+ posts = Post.all.merge!(:includes=>:comments).to_a
assert_equal 11, posts.size
end
def test_preloading_has_many_in_one_queries_when_database_has_no_limit_on_ids_it_can_handle
Post.connection.expects(:in_clause_length).at_least_once.returns(nil)
- posts = Post.scoped(:includes=>:comments).all
+ posts = Post.all.merge!(:includes=>:comments).to_a
assert_equal 11, posts.size
end
def test_preloading_habtm_in_multiple_queries_with_more_ids_than_database_can_handle
Post.connection.expects(:in_clause_length).at_least_once.returns(5)
- posts = Post.scoped(:includes=>:categories).all
+ posts = Post.all.merge!(:includes=>:categories).to_a
assert_equal 11, posts.size
end
def test_preloading_habtm_in_one_queries_when_database_has_no_limit_on_ids_it_can_handle
Post.connection.expects(:in_clause_length).at_least_once.returns(nil)
- posts = Post.scoped(:includes=>:categories).all
+ posts = Post.all.merge!(:includes=>:categories).to_a
assert_equal 11, posts.size
end
@@ -154,8 +149,8 @@ class EagerAssociationTest < ActiveRecord::TestCase
popular_post.readers.create!(:person => people(:michael))
popular_post.readers.create!(:person => people(:david))
- readers = Reader.scoped(:where => ["post_id = ?", popular_post.id],
- :includes => {:post => :comments}).all
+ readers = Reader.all.merge!(:where => ["post_id = ?", popular_post.id],
+ :includes => {:post => :comments}).to_a
readers.each do |reader|
assert_equal [comment], reader.post.comments
end
@@ -167,8 +162,8 @@ class EagerAssociationTest < ActiveRecord::TestCase
car_post.categories << categories(:technology)
comment = car_post.comments.create!(:body => "hmm")
- categories = Category.scoped(:where => { 'posts.id' => car_post.id },
- :includes => {:posts => :comments}).all
+ categories = Category.all.merge!(:where => { 'posts.id' => car_post.id },
+ :includes => {:posts => :comments}).to_a
categories.each do |category|
assert_equal [comment], category.posts[0].comments
end
@@ -186,7 +181,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_finding_with_includes_on_has_many_association_with_same_include_includes_only_once
author_id = authors(:david).id
- author = assert_queries(3) { Author.scoped(:includes => {:posts_with_comments => :comments}).find(author_id) } # find the author, then find the posts, then find the comments
+ author = assert_queries(3) { Author.all.merge!(:includes => {:posts_with_comments => :comments}).find(author_id) } # find the author, then find the posts, then find the comments
author.posts_with_comments.each do |post_with_comments|
assert_equal post_with_comments.comments.length, post_with_comments.comments.count
assert_nil post_with_comments.comments.to_a.uniq!
@@ -197,7 +192,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.scoped(:includes => {:post_about_thinking_with_last_comment => :last_comment}).find(author.id)} # find the author, then find the posts, then find the comments
+ author = assert_queries(3) { Author.all.merge!(:includes => {:post_about_thinking_with_last_comment => :last_comment}).find(author.id)} # 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
@@ -208,7 +203,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
post = posts(:welcome)
author = post.author
author_address = author.author_address
- post = assert_queries(3) { Post.scoped(:includes => {:author_with_address => :author_address}).find(post.id) } # find the post, then find the author, then find the address
+ post = assert_queries(3) { Post.all.merge!(:includes => {:author_with_address => :author_address}).find(post.id) } # 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
@@ -218,7 +213,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_finding_with_includes_on_null_belongs_to_association_with_same_include_includes_only_once
post = posts(:welcome)
post.update_attributes!(:author => nil)
- post = assert_queries(1) { Post.scoped(:includes => {:author_with_address => :author_address}).find(post.id) } # find the post, then find the author which is null so no query for the author or address
+ post = assert_queries(1) { Post.all.merge!(:includes => {:author_with_address => :author_address}).find(post.id) } # find the post, then find the author which is null so no query for the author or address
assert_no_queries do
assert_equal nil, post.author_with_address
end
@@ -227,56 +222,56 @@ class EagerAssociationTest < ActiveRecord::TestCase
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.scoped(:includes => :sponsorable).find(sponsor.id) }
+ sponsor = assert_queries(1) { Sponsor.all.merge!(:includes => :sponsorable).find(sponsor.id) }
assert_no_queries do
assert_equal nil, sponsor.sponsorable
end
end
def test_loading_from_an_association
- posts = authors(:david).posts.scoped(:includes => :comments, :order => "posts.id").all
+ posts = authors(:david).posts.merge(:includes => :comments, :order => "posts.id").to_a
assert_equal 2, posts.first.comments.size
end
def test_loading_from_an_association_that_has_a_hash_of_conditions
assert_nothing_raised do
- Author.scoped(:includes => :hello_posts_with_hash_conditions).all
+ Author.all.merge!(:includes => :hello_posts_with_hash_conditions).to_a
end
- assert !Author.scoped(:includes => :hello_posts_with_hash_conditions).find(authors(:david).id).hello_posts.empty?
+ assert !Author.all.merge!(:includes => :hello_posts_with_hash_conditions).find(authors(:david).id).hello_posts.empty?
end
def test_loading_with_no_associations
- assert_nil Post.scoped(:includes => :author).find(posts(:authorless).id).author
+ assert_nil Post.all.merge!(:includes => :author).find(posts(:authorless).id).author
end
def test_nested_loading_with_no_associations
assert_nothing_raised do
- Post.scoped(:includes => {:author => :author_addresss}).find(posts(:authorless).id)
+ Post.all.merge!(:includes => {:author => :author_addresss}).find(posts(:authorless).id)
end
end
def test_nested_loading_through_has_one_association
- aa = AuthorAddress.scoped(:includes => {:author => :posts}).find(author_addresses(:david_address).id)
+ aa = AuthorAddress.all.merge!(:includes => {:author => :posts}).find(author_addresses(:david_address).id)
assert_equal aa.author.posts.count, aa.author.posts.length
end
def test_nested_loading_through_has_one_association_with_order
- aa = AuthorAddress.scoped(:includes => {:author => :posts}, :order => 'author_addresses.id').find(author_addresses(:david_address).id)
+ aa = AuthorAddress.all.merge!(:includes => {:author => :posts}, :order => 'author_addresses.id').find(author_addresses(:david_address).id)
assert_equal aa.author.posts.count, aa.author.posts.length
end
def test_nested_loading_through_has_one_association_with_order_on_association
- aa = AuthorAddress.scoped(:includes => {:author => :posts}, :order => 'authors.id').find(author_addresses(:david_address).id)
+ aa = AuthorAddress.all.merge!(:includes => {:author => :posts}, :order => 'authors.id').find(author_addresses(:david_address).id)
assert_equal aa.author.posts.count, aa.author.posts.length
end
def test_nested_loading_through_has_one_association_with_order_on_nested_association
- aa = AuthorAddress.scoped(:includes => {:author => :posts}, :order => 'posts.id').find(author_addresses(:david_address).id)
+ aa = AuthorAddress.all.merge!(:includes => {:author => :posts}, :order => 'posts.id').find(author_addresses(:david_address).id)
assert_equal aa.author.posts.count, aa.author.posts.length
end
def test_nested_loading_through_has_one_association_with_conditions
- aa = AuthorAddress.references(:author_addresses).scoped(
+ aa = AuthorAddress.references(:author_addresses).merge(
:includes => {:author => :posts},
:where => "author_addresses.id > 0"
).find author_addresses(:david_address).id
@@ -284,7 +279,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_nested_loading_through_has_one_association_with_conditions_on_association
- aa = AuthorAddress.references(:authors).scoped(
+ aa = AuthorAddress.references(:authors).merge(
:includes => {:author => :posts},
:where => "authors.id > 0"
).find author_addresses(:david_address).id
@@ -292,7 +287,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_nested_loading_through_has_one_association_with_conditions_on_nested_association
- aa = AuthorAddress.references(:posts).scoped(
+ aa = AuthorAddress.references(:posts).merge(
:includes => {:author => :posts},
:where => "posts.id > 0"
).find author_addresses(:david_address).id
@@ -300,12 +295,12 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_belongs_to_and_foreign_keys
- pets = Pet.scoped(:includes => :owner).all
+ pets = Pet.all.merge!(:includes => :owner).to_a
assert_equal 3, pets.length
end
def test_eager_association_loading_with_belongs_to
- comments = Comment.scoped(:includes => :post).all
+ comments = Comment.all.merge!(:includes => :post).to_a
assert_equal 11, comments.length
titles = comments.map { |c| c.post.title }
assert titles.include?(posts(:welcome).title)
@@ -313,31 +308,31 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_belongs_to_and_limit
- comments = Comment.scoped(:includes => :post, :limit => 5, :order => 'comments.id').all
+ comments = Comment.all.merge!(:includes => :post, :limit => 5, :order => 'comments.id').to_a
assert_equal 5, comments.length
assert_equal [1,2,3,5,6], comments.collect { |c| c.id }
end
def test_eager_association_loading_with_belongs_to_and_limit_and_conditions
- comments = Comment.scoped(:includes => :post, :where => 'post_id = 4', :limit => 3, :order => 'comments.id').all
+ comments = Comment.all.merge!(:includes => :post, :where => 'post_id = 4', :limit => 3, :order => 'comments.id').to_a
assert_equal 3, comments.length
assert_equal [5,6,7], comments.collect { |c| c.id }
end
def test_eager_association_loading_with_belongs_to_and_limit_and_offset
- comments = Comment.scoped(:includes => :post, :limit => 3, :offset => 2, :order => 'comments.id').all
+ comments = Comment.all.merge!(:includes => :post, :limit => 3, :offset => 2, :order => 'comments.id').to_a
assert_equal 3, comments.length
assert_equal [3,5,6], comments.collect { |c| c.id }
end
def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_conditions
- comments = Comment.scoped(:includes => :post, :where => 'post_id = 4', :limit => 3, :offset => 1, :order => 'comments.id').all
+ comments = Comment.all.merge!(:includes => :post, :where => 'post_id = 4', :limit => 3, :offset => 1, :order => 'comments.id').to_a
assert_equal 3, comments.length
assert_equal [6,7,8], comments.collect { |c| c.id }
end
def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_conditions_array
- comments = Comment.scoped(:includes => :post, :where => ['post_id = ?',4], :limit => 3, :offset => 1, :order => 'comments.id').all
+ comments = Comment.all.merge!(:includes => :post, :where => ['post_id = ?',4], :limit => 3, :offset => 1, :order => 'comments.id').to_a
assert_equal 3, comments.length
assert_equal [6,7,8], comments.collect { |c| c.id }
end
@@ -345,7 +340,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_association_loading_with_belongs_to_and_conditions_string_with_unquoted_table_name
assert_nothing_raised do
ActiveSupport::Deprecation.silence do
- Comment.scoped(:includes => :post, :where => ['posts.id = ?',4]).all
+ Comment.all.merge!(:includes => :post, :where => ['posts.id = ?',4]).to_a
end
end
end
@@ -353,7 +348,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_association_loading_with_belongs_to_and_conditions_hash
comments = []
assert_nothing_raised do
- comments = Comment.scoped(:includes => :post, :where => {:posts => {:id => 4}}, :limit => 3, :order => 'comments.id').all
+ comments = Comment.all.merge!(:includes => :post, :where => {:posts => {:id => 4}}, :limit => 3, :order => 'comments.id').to_a
end
assert_equal 3, comments.length
assert_equal [5,6,7], comments.collect { |c| c.id }
@@ -366,14 +361,14 @@ class EagerAssociationTest < ActiveRecord::TestCase
quoted_posts_id= Comment.connection.quote_table_name('posts') + '.' + Comment.connection.quote_column_name('id')
assert_nothing_raised do
ActiveSupport::Deprecation.silence do
- Comment.scoped(:includes => :post, :where => ["#{quoted_posts_id} = ?",4]).all
+ Comment.all.merge!(:includes => :post, :where => ["#{quoted_posts_id} = ?",4]).to_a
end
end
end
def test_eager_association_loading_with_belongs_to_and_order_string_with_unquoted_table_name
assert_nothing_raised do
- Comment.scoped(:includes => :post, :order => 'posts.id').all
+ Comment.all.merge!(:includes => :post, :order => 'posts.id').to_a
end
end
@@ -381,25 +376,25 @@ class EagerAssociationTest < ActiveRecord::TestCase
quoted_posts_id= Comment.connection.quote_table_name('posts') + '.' + Comment.connection.quote_column_name('id')
assert_nothing_raised do
ActiveSupport::Deprecation.silence do
- Comment.scoped(:includes => :post, :order => quoted_posts_id).all
+ Comment.all.merge!(:includes => :post, :order => quoted_posts_id).to_a
end
end
end
def test_eager_association_loading_with_belongs_to_and_limit_and_multiple_associations
- posts = Post.scoped(:includes => [:author, :very_special_comment], :limit => 1, :order => 'posts.id').all
+ posts = Post.all.merge!(:includes => [:author, :very_special_comment], :limit => 1, :order => 'posts.id').to_a
assert_equal 1, posts.length
assert_equal [1], posts.collect { |p| p.id }
end
def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_multiple_associations
- posts = Post.scoped(:includes => [:author, :very_special_comment], :limit => 1, :offset => 1, :order => 'posts.id').all
+ posts = Post.all.merge!(:includes => [:author, :very_special_comment], :limit => 1, :offset => 1, :order => 'posts.id').to_a
assert_equal 1, posts.length
assert_equal [2], posts.collect { |p| p.id }
end
def test_eager_association_loading_with_belongs_to_inferred_foreign_key_from_association_name
- author_favorite = AuthorFavorite.scoped(:includes => :favorite_author).first
+ author_favorite = AuthorFavorite.all.merge!(:includes => :favorite_author).first
assert_equal authors(:mary), assert_no_queries { author_favorite.favorite_author }
end
@@ -410,26 +405,26 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_load_has_one_quotes_table_and_column_names
- michael = Person.scoped(:includes => :favourite_reference).find(people(:michael))
+ michael = Person.all.merge!(:includes => :favourite_reference).find(people(:michael))
references(:michael_unicyclist)
assert_no_queries{ assert_equal references(:michael_unicyclist), michael.favourite_reference}
end
def test_eager_load_has_many_quotes_table_and_column_names
- michael = Person.scoped(:includes => :references).find(people(:michael))
+ michael = Person.all.merge!(:includes => :references).find(people(:michael))
references(:michael_magician,:michael_unicyclist)
assert_no_queries{ assert_equal references(:michael_magician,:michael_unicyclist), michael.references.sort_by(&:id) }
end
def test_eager_load_has_many_through_quotes_table_and_column_names
- michael = Person.scoped(:includes => :jobs).find(people(:michael))
+ michael = Person.all.merge!(:includes => :jobs).find(people(:michael))
jobs(:magician, :unicyclist)
assert_no_queries{ assert_equal jobs(:unicyclist, :magician), michael.jobs.sort_by(&:id) }
end
def test_eager_load_has_many_with_string_keys
subscriptions = subscriptions(:webster_awdr, :webster_rfr)
- subscriber =Subscriber.scoped(:includes => :subscriptions).find(subscribers(:second).id)
+ subscriber =Subscriber.all.merge!(:includes => :subscriptions).find(subscribers(:second).id)
assert_equal subscriptions, subscriber.subscriptions.sort_by(&:id)
end
@@ -447,25 +442,25 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_load_has_many_through_with_string_keys
books = books(:awdr, :rfr)
- subscriber = Subscriber.scoped(:includes => :books).find(subscribers(:second).id)
+ subscriber = Subscriber.all.merge!(:includes => :books).find(subscribers(:second).id)
assert_equal books, subscriber.books.sort_by(&:id)
end
def test_eager_load_belongs_to_with_string_keys
subscriber = subscribers(:second)
- subscription = Subscription.scoped(:includes => :subscriber).find(subscriptions(:webster_awdr).id)
+ subscription = Subscription.all.merge!(:includes => :subscriber).find(subscriptions(:webster_awdr).id)
assert_equal subscriber, subscription.subscriber
end
def test_eager_association_loading_with_explicit_join
- posts = Post.scoped(:includes => :comments, :joins => "INNER JOIN authors ON posts.author_id = authors.id AND authors.name = 'Mary'", :limit => 1, :order => 'author_id').all
+ posts = Post.all.merge!(:includes => :comments, :joins => "INNER JOIN authors ON posts.author_id = authors.id AND authors.name = 'Mary'", :limit => 1, :order => 'author_id').to_a
assert_equal 1, posts.length
end
def test_eager_with_has_many_through
- posts_with_comments = people(:michael).posts.scoped(:includes => :comments, :order => 'posts.id').all
- posts_with_author = people(:michael).posts.scoped(:includes => :author, :order => 'posts.id').all
- posts_with_comments_and_author = people(:michael).posts.scoped(:includes => [ :comments, :author ], :order => 'posts.id').all
+ posts_with_comments = people(:michael).posts.merge(:includes => :comments, :order => 'posts.id').to_a
+ posts_with_author = people(:michael).posts.merge(:includes => :author, :order => 'posts.id').to_a
+ posts_with_comments_and_author = people(:michael).posts.merge(:includes => [ :comments, :author ], :order => 'posts.id').to_a
assert_equal 2, posts_with_comments.inject(0) { |sum, post| sum += post.comments.size }
assert_equal authors(:david), assert_no_queries { posts_with_author.first.author }
assert_equal authors(:david), assert_no_queries { posts_with_comments_and_author.first.author }
@@ -476,32 +471,32 @@ class EagerAssociationTest < ActiveRecord::TestCase
Post.create!(:author => author, :title => "TITLE", :body => "BODY")
author.author_favorites.create(:favorite_author_id => 1)
author.author_favorites.create(:favorite_author_id => 2)
- posts_with_author_favorites = author.posts.scoped(:includes => :author_favorites).all
+ posts_with_author_favorites = author.posts.merge(:includes => :author_favorites).to_a
assert_no_queries { posts_with_author_favorites.first.author_favorites.first.author_id }
end
def test_eager_with_has_many_through_an_sti_join_model
- author = Author.scoped(:includes => :special_post_comments, :order => 'authors.id').first
+ author = Author.all.merge!(:includes => :special_post_comments, :order => 'authors.id').first
assert_equal [comments(:does_it_hurt)], assert_no_queries { author.special_post_comments }
end
def test_eager_with_has_many_through_an_sti_join_model_with_conditions_on_both
- author = Author.scoped(:includes => :special_nonexistant_post_comments, :order => 'authors.id').first
+ author = Author.all.merge!(:includes => :special_nonexistant_post_comments, :order => 'authors.id').first
assert_equal [], author.special_nonexistant_post_comments
end
def test_eager_with_has_many_through_join_model_with_conditions
- assert_equal Author.scoped(:includes => :hello_post_comments,
+ assert_equal Author.all.merge!(:includes => :hello_post_comments,
:order => 'authors.id').first.hello_post_comments.sort_by(&:id),
- Author.scoped(:order => 'authors.id').first.hello_post_comments.sort_by(&:id)
+ Author.all.merge!(:order => 'authors.id').first.hello_post_comments.sort_by(&:id)
end
def test_eager_with_has_many_through_join_model_with_conditions_on_top_level
- assert_equal comments(:more_greetings), Author.scoped(:includes => :comments_with_order_and_conditions).find(authors(:david).id).comments_with_order_and_conditions.first
+ assert_equal comments(:more_greetings), Author.all.merge!(:includes => :comments_with_order_and_conditions).find(authors(:david).id).comments_with_order_and_conditions.first
end
def test_eager_with_has_many_through_join_model_with_include
- author_comments = Author.scoped(:includes => :comments_with_include).find(authors(:david).id).comments_with_include.to_a
+ author_comments = Author.all.merge!(:includes => :comments_with_include).find(authors(:david).id).comments_with_include.to_a
assert_no_queries do
author_comments.first.post.title
end
@@ -509,7 +504,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_has_many_through_with_conditions_join_model_with_include
post_tags = Post.find(posts(:welcome).id).misc_tags
- eager_post_tags = Post.scoped(:includes => :misc_tags).find(1).misc_tags
+ eager_post_tags = Post.all.merge!(:includes => :misc_tags).find(1).misc_tags
assert_equal post_tags, eager_post_tags
end
@@ -520,16 +515,16 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_with_has_many_and_limit
- posts = Post.scoped(:order => 'posts.id asc', :includes => [ :author, :comments ], :limit => 2).all
+ posts = Post.all.merge!(:order => 'posts.id asc', :includes => [ :author, :comments ], :limit => 2).to_a
assert_equal 2, posts.size
assert_equal 3, posts.inject(0) { |sum, post| sum += post.comments.size }
end
def test_eager_with_has_many_and_limit_and_conditions
if current_adapter?(:OpenBaseAdapter)
- posts = Post.scoped(:includes => [ :author, :comments ], :limit => 2, :where => "FETCHBLOB(posts.body) = 'hello'", :order => "posts.id").all
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => "FETCHBLOB(posts.body) = 'hello'", :order => "posts.id").to_a
else
- posts = Post.scoped(:includes => [ :author, :comments ], :limit => 2, :where => "posts.body = 'hello'", :order => "posts.id").all
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => "posts.body = 'hello'", :order => "posts.id").to_a
end
assert_equal 2, posts.size
assert_equal [4,5], posts.collect { |p| p.id }
@@ -537,9 +532,9 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_has_many_and_limit_and_conditions_array
if current_adapter?(:OpenBaseAdapter)
- posts = Post.scoped(:includes => [ :author, :comments ], :limit => 2, :where => [ "FETCHBLOB(posts.body) = ?", 'hello' ], :order => "posts.id").all
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => [ "FETCHBLOB(posts.body) = ?", 'hello' ], :order => "posts.id").to_a
else
- posts = Post.scoped(:includes => [ :author, :comments ], :limit => 2, :where => [ "posts.body = ?", 'hello' ], :order => "posts.id").all
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => [ "posts.body = ?", 'hello' ], :order => "posts.id").to_a
end
assert_equal 2, posts.size
assert_equal [4,5], posts.collect { |p| p.id }
@@ -547,7 +542,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_has_many_and_limit_and_conditions_array_on_the_eagers
posts = ActiveSupport::Deprecation.silence do
- Post.scoped(:includes => [ :author, :comments ], :limit => 2, :where => [ "authors.name = ?", 'David' ]).all
+ Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => [ "authors.name = ?", 'David' ]).to_a
end
assert_equal 2, posts.size
@@ -558,34 +553,34 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_with_has_many_and_limit_and_high_offset
- posts = Post.scoped(:includes => [ :author, :comments ], :limit => 2, :offset => 10, :where => { 'authors.name' => 'David' }).all
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :offset => 10, :where => { 'authors.name' => 'David' }).to_a
assert_equal 0, posts.size
end
def test_eager_with_has_many_and_limit_and_high_offset_and_multiple_array_conditions
assert_queries(1) do
posts = Post.references(:authors, :comments).
- scoped(:includes => [ :author, :comments ], :limit => 2, :offset => 10,
- :where => [ "authors.name = ? and comments.body = ?", 'David', 'go crazy' ]).all
+ merge(:includes => [ :author, :comments ], :limit => 2, :offset => 10,
+ :where => [ "authors.name = ? and comments.body = ?", 'David', 'go crazy' ]).to_a
assert_equal 0, posts.size
end
end
def test_eager_with_has_many_and_limit_and_high_offset_and_multiple_hash_conditions
assert_queries(1) do
- posts = Post.scoped(:includes => [ :author, :comments ], :limit => 2, :offset => 10,
- :where => { 'authors.name' => 'David', 'comments.body' => 'go crazy' }).all
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :offset => 10,
+ :where => { 'authors.name' => 'David', 'comments.body' => 'go crazy' }).to_a
assert_equal 0, posts.size
end
end
def test_count_eager_with_has_many_and_limit_and_high_offset
- posts = Post.scoped(:includes => [ :author, :comments ], :limit => 2, :offset => 10, :where => { 'authors.name' => 'David' }).count(:all)
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :offset => 10, :where => { 'authors.name' => 'David' }).count(:all)
assert_equal 0, posts
end
def test_eager_with_has_many_and_limit_with_no_results
- posts = Post.scoped(:includes => [ :author, :comments ], :limit => 2, :where => "posts.title = 'magic forest'").all
+ posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => "posts.title = 'magic forest'").to_a
assert_equal 0, posts.size
end
@@ -602,7 +597,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_with_has_and_belongs_to_many_and_limit
- posts = Post.scoped(:includes => :categories, :order => "posts.id", :limit => 3).all
+ posts = Post.all.merge!(:includes => :categories, :order => "posts.id", :limit => 3).to_a
assert_equal 3, posts.size
assert_equal 2, posts[0].categories.size
assert_equal 1, posts[1].categories.size
@@ -668,7 +663,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_association_loading_with_habtm
- posts = Post.scoped(:includes => :categories, :order => "posts.id").all
+ posts = Post.all.merge!(:includes => :categories, :order => "posts.id").to_a
assert_equal 2, posts[0].categories.size
assert_equal 1, posts[1].categories.size
assert_equal 0, posts[2].categories.size
@@ -677,23 +672,23 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_eager_with_inheritance
- SpecialPost.scoped(:includes => [ :comments ]).all
+ SpecialPost.all.merge!(:includes => [ :comments ]).to_a
end
def test_eager_has_one_with_association_inheritance
- post = Post.scoped(:includes => [ :very_special_comment ]).find(4)
+ post = Post.all.merge!(:includes => [ :very_special_comment ]).find(4)
assert_equal "VerySpecialComment", post.very_special_comment.class.to_s
end
def test_eager_has_many_with_association_inheritance
- post = Post.scoped(:includes => [ :special_comments ]).find(4)
+ post = Post.all.merge!(:includes => [ :special_comments ]).find(4)
post.special_comments.each do |special_comment|
assert special_comment.is_a?(SpecialComment)
end
end
def test_eager_habtm_with_association_inheritance
- post = Post.scoped(:includes => [ :special_categories ]).find(6)
+ post = Post.all.merge!(:includes => [ :special_categories ]).find(6)
assert_equal 1, post.special_categories.size
post.special_categories.each do |special_category|
assert_equal "SpecialCategory", special_category.class.to_s
@@ -702,7 +697,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_has_one_dependent_does_not_destroy_dependent
assert_not_nil companies(:first_firm).account
- f = Firm.scoped(:includes => :account,
+ f = Firm.all.merge!(:includes => :account,
:where => ["companies.name = ?", "37signals"]).first
assert_not_nil f.account
assert_equal companies(:first_firm, :reload).account, f.account
@@ -717,22 +712,22 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_invalid_association_reference
assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
- Post.scoped(:includes=> :monkeys ).find(6)
+ Post.all.merge!(:includes=> :monkeys ).find(6)
}
assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
- Post.scoped(:includes=>[ :monkeys ]).find(6)
+ Post.all.merge!(:includes=>[ :monkeys ]).find(6)
}
assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
- Post.scoped(:includes=>[ 'monkeys' ]).find(6)
+ Post.all.merge!(:includes=>[ 'monkeys' ]).find(6)
}
assert_raise(ActiveRecord::ConfigurationError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys, :elephants") {
- Post.scoped(:includes=>[ :monkeys, :elephants ]).find(6)
+ Post.all.merge!(:includes=>[ :monkeys, :elephants ]).find(6)
}
end
def test_eager_with_default_scope
developer = EagerDeveloperWithDefaultScope.where(:name => 'David').first
- projects = Project.order(:id).all
+ projects = Project.order(:id).to_a
assert_no_queries do
assert_equal(projects, developer.projects)
end
@@ -740,7 +735,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_default_scope_as_class_method
developer = EagerDeveloperWithClassMethodDefaultScope.where(:name => 'David').first
- projects = Project.order(:id).all
+ projects = Project.order(:id).to_a
assert_no_queries do
assert_equal(projects, developer.projects)
end
@@ -748,7 +743,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_default_scope_as_lambda
developer = EagerDeveloperWithLambdaDefaultScope.where(:name => 'David').first
- projects = Project.order(:id).all
+ projects = Project.order(:id).to_a
assert_no_queries do
assert_equal(projects, developer.projects)
end
@@ -756,7 +751,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_default_scope_as_block
developer = EagerDeveloperWithBlockDefaultScope.where(:name => 'David').first
- projects = Project.order(:id).all
+ projects = Project.order(:id).to_a
assert_no_queries do
assert_equal(projects, developer.projects)
end
@@ -764,58 +759,58 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_with_default_scope_as_callable
developer = EagerDeveloperWithCallableDefaultScope.where(:name => 'David').first
- projects = Project.order(:id).all
+ projects = Project.order(:id).to_a
assert_no_queries do
assert_equal(projects, developer.projects)
end
end
def find_all_ordered(className, include=nil)
- className.scoped(:order=>"#{className.table_name}.#{className.primary_key}", :includes=>include).all
+ className.all.merge!(:order=>"#{className.table_name}.#{className.primary_key}", :includes=>include).to_a
end
def test_limited_eager_with_order
assert_equal(
posts(:thinking, :sti_comments),
- Post.scoped(
+ Post.all.merge!(
:includes => [:author, :comments], :where => { 'authors.name' => 'David' },
:order => 'UPPER(posts.title)', :limit => 2, :offset => 1
- ).all
+ ).to_a
)
assert_equal(
posts(:sti_post_and_comments, :sti_comments),
- Post.scoped(
+ Post.all.merge!(
:includes => [:author, :comments], :where => { 'authors.name' => 'David' },
:order => 'UPPER(posts.title) DESC', :limit => 2, :offset => 1
- ).all
+ ).to_a
)
end
def test_limited_eager_with_multiple_order_columns
assert_equal(
posts(:thinking, :sti_comments),
- Post.scoped(
+ Post.all.merge!(
:includes => [:author, :comments], :where => { 'authors.name' => 'David' },
:order => ['UPPER(posts.title)', 'posts.id'], :limit => 2, :offset => 1
- ).all
+ ).to_a
)
assert_equal(
posts(:sti_post_and_comments, :sti_comments),
- Post.scoped(
+ Post.all.merge!(
:includes => [:author, :comments], :where => { 'authors.name' => 'David' },
:order => ['UPPER(posts.title) DESC', 'posts.id'], :limit => 2, :offset => 1
- ).all
+ ).to_a
)
end
def test_limited_eager_with_numeric_in_association
assert_equal(
people(:david, :susan),
- Person.references(:number1_fans_people).scoped(
+ Person.references(:number1_fans_people).merge(
:includes => [:readers, :primary_contact, :number1_fan],
:where => "number1_fans_people.first_name like 'M%'",
:order => 'people.id', :limit => 2, :offset => 0
- ).all
+ ).to_a
)
end
@@ -828,9 +823,9 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_polymorphic_type_condition
- post = Post.scoped(:includes => :taggings).find(posts(:thinking).id)
+ post = Post.all.merge!(:includes => :taggings).find(posts(:thinking).id)
assert post.taggings.include?(taggings(:thinking_general))
- post = SpecialPost.scoped(:includes => :taggings).find(posts(:thinking).id)
+ post = SpecialPost.all.merge!(:includes => :taggings).find(posts(:thinking).id)
assert post.taggings.include?(taggings(:thinking_general))
end
@@ -881,13 +876,13 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
end
def test_eager_with_valid_association_as_string_not_symbol
- assert_nothing_raised { Post.scoped(:includes => 'comments').all }
+ assert_nothing_raised { Post.all.merge!(:includes => 'comments').to_a }
end
def test_eager_with_floating_point_numbers
assert_queries(2) do
# Before changes, the floating point numbers will be interpreted as table names and will cause this to run in one query
- Comment.scoped(:where => "123.456 = 123.456", :includes => :post).all
+ Comment.all.merge!(:where => "123.456 = 123.456", :includes => :post).to_a
end
end
@@ -941,21 +936,21 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_load_with_sti_sharing_association
assert_queries(2) do #should not do 1 query per subclass
- Comment.includes(:post).all
+ Comment.includes(:post).to_a
end
end
def test_conditions_on_join_table_with_include_and_limit
- assert_equal 3, Developer.scoped(:includes => 'projects', :where => { 'developers_projects.access_level' => 1 }, :limit => 5).all.size
+ assert_equal 3, Developer.all.merge!(:includes => 'projects', :where => { 'developers_projects.access_level' => 1 }, :limit => 5).to_a.size
end
def test_order_on_join_table_with_include_and_limit
- assert_equal 5, Developer.scoped(:includes => 'projects', :order => 'developers_projects.joined_on DESC', :limit => 5).all.size
+ assert_equal 5, Developer.all.merge!(:includes => 'projects', :order => 'developers_projects.joined_on DESC', :limit => 5).to_a.size
end
def test_eager_loading_with_order_on_joined_table_preloads
posts = assert_queries(2) do
- Post.scoped(:joins => :comments, :includes => :author, :order => 'comments.id DESC').all
+ Post.all.merge!(:joins => :comments, :includes => :author, :order => 'comments.id DESC').to_a
end
assert_equal posts(:eager_other), posts[1]
assert_equal authors(:mary), assert_no_queries { posts[1].author}
@@ -963,64 +958,60 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_eager_loading_with_conditions_on_joined_table_preloads
posts = assert_queries(2) do
- Post.scoped(:select => 'distinct posts.*', :includes => :author, :joins => [:comments], :where => "comments.body like 'Thank you%'", :order => 'posts.id').all
+ Post.all.merge!(:select => 'distinct posts.*', :includes => :author, :joins => [:comments], :where => "comments.body like 'Thank you%'", :order => 'posts.id').to_a
end
assert_equal [posts(:welcome)], posts
assert_equal authors(:david), assert_no_queries { posts[0].author}
posts = assert_queries(2) do
- Post.scoped(:select => 'distinct posts.*', :includes => :author, :joins => [:comments], :where => "comments.body like 'Thank you%'", :order => 'posts.id').all
+ Post.all.merge!(:select => 'distinct posts.*', :includes => :author, :joins => [:comments], :where => "comments.body like 'Thank you%'", :order => 'posts.id').to_a
end
assert_equal [posts(:welcome)], posts
assert_equal authors(:david), assert_no_queries { posts[0].author}
posts = assert_queries(2) do
- Post.scoped(:includes => :author, :joins => {:taggings => :tag}, :where => "tags.name = 'General'", :order => 'posts.id').all
+ Post.all.merge!(:includes => :author, :joins => {:taggings => :tag}, :where => "tags.name = 'General'", :order => 'posts.id').to_a
end
assert_equal posts(:welcome, :thinking), posts
posts = assert_queries(2) do
- Post.scoped(:includes => :author, :joins => {:taggings => {:tag => :taggings}}, :where => "taggings_tags.super_tag_id=2", :order => 'posts.id').all
+ Post.all.merge!(:includes => :author, :joins => {:taggings => {:tag => :taggings}}, :where => "taggings_tags.super_tag_id=2", :order => 'posts.id').to_a
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.scoped(:select => 'distinct posts.*', :includes => :author, :joins => "INNER JOIN comments on comments.post_id = posts.id", :where => "comments.body like 'Thank you%'", :order => 'posts.id').all
+ Post.all.merge!(:select => 'distinct posts.*', :includes => :author, :joins => "INNER JOIN comments on comments.post_id = posts.id", :where => "comments.body like 'Thank you%'", :order => 'posts.id').to_a
end
assert_equal [posts(:welcome)], posts
assert_equal authors(:david), assert_no_queries { posts[0].author}
posts = assert_queries(2) do
- Post.scoped(:select => 'distinct posts.*', :includes => :author, :joins => ["INNER JOIN comments on comments.post_id = posts.id"], :where => "comments.body like 'Thank you%'", :order => 'posts.id').all
+ Post.all.merge!(:select => 'distinct posts.*', :includes => :author, :joins => ["INNER JOIN comments on comments.post_id = posts.id"], :where => "comments.body like 'Thank you%'", :order => 'posts.id').to_a
end
assert_equal [posts(:welcome)], posts
assert_equal authors(:david), assert_no_queries { posts[0].author}
-
end
def test_eager_loading_with_select_on_joined_table_preloads
posts = assert_queries(2) do
- Post.scoped(:select => 'posts.*, authors.name as author_name', :includes => :comments, :joins => :author, :order => 'posts.id').all
+ Post.all.merge!(:select => 'posts.*, authors.name as author_name', :includes => :comments, :joins => :author, :order => 'posts.id').to_a
end
assert_equal 'David', posts[0].author_name
assert_equal posts(:welcome).comments, assert_no_queries { posts[0].comments}
end
def test_eager_loading_with_conditions_on_join_model_preloads
- Author.columns
-
authors = assert_queries(2) do
- Author.scoped(:includes => :author_address, :joins => :comments, :where => "posts.title like 'Welcome%'").all
+ Author.all.merge!(:includes => :author_address, :joins => :comments, :where => "posts.title like 'Welcome%'").to_a
end
assert_equal authors(:david), authors[0]
assert_equal author_addresses(:david_address), authors[0].author_address
end
def test_preload_belongs_to_uses_exclusive_scope
- people = Person.males.scoped(:includes => :primary_contact).all
+ people = Person.males.merge(:includes => :primary_contact).to_a
assert_not_equal people.length, 0
people.each do |person|
assert_no_queries {assert_not_nil person.primary_contact}
@@ -1029,7 +1020,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_preload_has_many_uses_exclusive_scope
- people = Person.males.includes(:agents).all
+ people = Person.males.includes(:agents).to_a
people.each do |person|
assert_equal Person.find(person.id).agents, person.agents
end
@@ -1047,9 +1038,9 @@ class EagerAssociationTest < ActiveRecord::TestCase
expected = Firm.find(1).clients_using_primary_key.sort_by(&:name)
# Oracle adapter truncates alias to 30 characters
if current_adapter?(:OracleAdapter)
- firm = Firm.scoped(:includes => :clients_using_primary_key, :order => 'clients_using_primary_keys_companies'[0,30]+'.name').find(1)
+ firm = Firm.all.merge!(:includes => :clients_using_primary_key, :order => 'clients_using_primary_keys_companies'[0,30]+'.name').find(1)
else
- firm = Firm.scoped(:includes => :clients_using_primary_key, :order => 'clients_using_primary_keys_companies.name').find(1)
+ firm = Firm.all.merge!(:includes => :clients_using_primary_key, :order => 'clients_using_primary_keys_companies.name').find(1)
end
assert_no_queries do
assert_equal expected, firm.clients_using_primary_key
@@ -1058,7 +1049,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_preload_has_one_using_primary_key
expected = accounts(:signals37)
- firm = Firm.scoped(:includes => :account_using_primary_key, :order => 'companies.id').first
+ firm = Firm.all.merge!(:includes => :account_using_primary_key, :order => 'companies.id').first
assert_no_queries do
assert_equal expected, firm.account_using_primary_key
end
@@ -1066,7 +1057,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
def test_include_has_one_using_primary_key
expected = accounts(:signals37)
- firm = Firm.scoped(:includes => :account_using_primary_key, :order => 'accounts.id').all.detect {|f| f.id == 1}
+ firm = Firm.all.merge!(:includes => :account_using_primary_key, :order => 'accounts.id').to_a.detect {|f| f.id == 1}
assert_no_queries do
assert_equal expected, firm.account_using_primary_key
end
@@ -1130,7 +1121,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
end
def test_deep_including_through_habtm
- posts = Post.scoped(:includes => {:categories => :categorizations}, :order => "posts.id").all
+ posts = Post.all.merge!(:includes => {:categories => :categorizations}, :order => "posts.id").to_a
assert_no_queries { assert_equal 2, posts[0].categories[0].categorizations.length }
assert_no_queries { assert_equal 1, posts[0].categories[1].categorizations.length }
assert_no_queries { assert_equal 2, posts[1].categories[0].categorizations.length }
diff --git a/activerecord/test/cases/associations/extension_test.rb b/activerecord/test/cases/associations/extension_test.rb
index d7c489c2b5..bd5a426ca8 100644
--- a/activerecord/test/cases/associations/extension_test.rb
+++ b/activerecord/test/cases/associations/extension_test.rb
@@ -64,14 +64,14 @@ class AssociationsExtensionsTest < ActiveRecord::TestCase
def test_proxy_association_after_scoped
post = posts(:welcome)
assert_equal post.association(:comments), post.comments.the_association
- assert_equal post.association(:comments), post.comments.scoped.the_association
+ assert_equal post.association(:comments), post.comments.where('1=1').the_association
end
private
def extension_name(model)
- builder = ActiveRecord::Associations::Builder::HasMany.new(model, :association_name, {}) { }
+ builder = ActiveRecord::Associations::Builder::HasMany.new(model, :association_name, nil, {}) { }
builder.send(:wrap_block_extension)
- builder.options[:extend].first.name
+ builder.extension_module.name
end
end
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 ed1caa2ef5..f3520d43e0 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
@@ -67,12 +67,15 @@ end
class DeveloperWithCounterSQL < ActiveRecord::Base
self.table_name = 'developers'
- has_and_belongs_to_many :projects,
- :class_name => "DeveloperWithCounterSQL",
- :join_table => "developers_projects",
- :association_foreign_key => "project_id",
- :foreign_key => "developer_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}" }
+
+ ActiveSupport::Deprecation.silence do
+ has_and_belongs_to_many :projects,
+ :class_name => "DeveloperWithCounterSQL",
+ :join_table => "developers_projects",
+ :association_foreign_key => "project_id",
+ :foreign_key => "developer_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
end
class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
@@ -356,7 +359,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
def test_deleting_array
david = Developer.find(1)
david.projects.reload
- david.projects.delete(Project.all)
+ david.projects.delete(Project.all.to_a)
assert_equal 0, david.projects.size
assert_equal 0, david.projects(true).size
end
@@ -423,7 +426,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
def test_destroying_many
david = Developer.find(1)
david.projects.reload
- projects = Project.all
+ projects = Project.all.to_a
assert_no_difference "Project.count" do
david.projects.destroy(*projects)
@@ -555,21 +558,21 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
def test_find_with_merged_options
assert_equal 1, projects(:active_record).limited_developers.size
- assert_equal 1, projects(:active_record).limited_developers.all.size
- assert_equal 3, projects(:active_record).limited_developers.limit(nil).all.size
+ assert_equal 1, projects(:active_record).limited_developers.to_a.size
+ assert_equal 3, projects(:active_record).limited_developers.limit(nil).to_a.size
end
def test_dynamic_find_should_respect_association_order
# Developers are ordered 'name DESC, id DESC'
high_id_jamis = projects(:active_record).developers.create(:name => 'Jamis')
- assert_equal high_id_jamis, projects(:active_record).developers.scoped(:where => "name = 'Jamis'").first
+ assert_equal high_id_jamis, projects(:active_record).developers.merge(:where => "name = 'Jamis'").first
assert_equal high_id_jamis, projects(:active_record).developers.find_by_name('Jamis')
end
- def test_find_should_append_to_association_order
+ def test_find_should_prepend_to_association_order
ordered_developers = projects(:active_record).developers.order('projects.id')
- assert_equal ['developers.name desc, developers.id desc', 'projects.id'], ordered_developers.order_values
+ assert_equal ['projects.id', 'developers.name desc, developers.id desc'], ordered_developers.order_values
end
def test_dynamic_find_all_should_respect_readonly_access
@@ -590,7 +593,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
end
def test_find_in_association_with_options
- developers = projects(:active_record).developers.all
+ developers = projects(:active_record).developers.to_a
assert_equal 3, developers.size
assert_equal developers(:poor_jamis), projects(:active_record).developers.where("salary < 10000").first
@@ -636,7 +639,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
project = SpecialProject.create("name" => "Special Project")
assert developer.save
developer.projects << project
- developer.update_column("name", "Bruza")
+ developer.update_columns("name" => "Bruza")
assert_equal 1, Developer.connection.select_value(<<-end_sql).to_i
SELECT count(*) FROM developers_projects
WHERE project_id = #{project.id}
@@ -668,7 +671,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
def test_join_table_alias
assert_equal(
3,
- Developer.references(:developers_projects_join).scoped(
+ Developer.references(:developers_projects_join).merge(
:includes => {:projects => :developers},
:where => 'developers_projects_join.joined_on IS NOT NULL'
).to_a.size
@@ -684,7 +687,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
assert_equal(
3,
- Developer.references(:developers_projects_join).scoped(
+ Developer.references(:developers_projects_join).merge(
:includes => {:projects => :developers}, :where => 'developers_projects_join.joined_on IS NOT NULL',
:group => group.join(",")
).to_a.size
@@ -692,8 +695,8 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
end
def test_find_grouped
- all_posts_from_category1 = Post.scoped(:where => "category_id = 1", :joins => :categories).all
- grouped_posts_of_category1 = Post.scoped(:where => "category_id = 1", :group => "author_id", :select => 'count(posts.id) as posts_count', :joins => :categories).all
+ all_posts_from_category1 = Post.all.merge!(:where => "category_id = 1", :joins => :categories).to_a
+ grouped_posts_of_category1 = Post.all.merge!(:where => "category_id = 1", :group => "author_id", :select => 'count(posts.id) as posts_count', :joins => :categories).to_a
assert_equal 5, all_posts_from_category1.size
assert_equal 2, grouped_posts_of_category1.size
end
@@ -773,9 +776,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
def test_self_referential_habtm_without_foreign_key_set_should_raise_exception
assert_raise(ActiveRecord::HasAndBelongsToManyAssociationForeignKeyNeeded) {
- Member.class_eval do
- has_and_belongs_to_many :friends, :class_name => "Member", :join_table => "member_friends"
- end
+ SelfMember.new.friends
}
end
@@ -817,11 +818,14 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
# clear cache possibly created by other tests
david.projects.reset_column_information
- assert_queries(1) { david.projects.columns; david.projects.columns }
+ assert_queries(:any) { david.projects.columns }
+ assert_no_queries { 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(:any) { david.projects.columns }
+ assert_no_queries { david.projects.columns }
end
def test_attributes_are_being_set_when_initialized_from_habm_association_with_where_clause
@@ -840,4 +844,16 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
developer = project.developers.build
assert project.developers.include?(developer)
end
+
+ test ":insert_sql is deprecated" do
+ klass = Class.new(ActiveRecord::Base)
+ def klass.name; 'Foo'; end
+ assert_deprecated { klass.has_and_belongs_to_many :posts, :insert_sql => 'lol' }
+ end
+
+ test ":delete_sql is deprecated" do
+ klass = Class.new(ActiveRecord::Base)
+ def klass.name; 'Foo'; end
+ assert_deprecated { klass.has_and_belongs_to_many :posts, :delete_sql => 'lol' }
+ end
end
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index 0d8f311117..04714f42e9 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -22,7 +22,9 @@ require 'models/engine'
class HasManyAssociationsTestForCountWithFinderSql < ActiveRecord::TestCase
class Invoice < ActiveRecord::Base
- has_many :custom_line_items, :class_name => 'LineItem', :finder_sql => "SELECT line_items.* from line_items"
+ ActiveSupport::Deprecation.silence do
+ has_many :custom_line_items, :class_name => 'LineItem', :finder_sql => "SELECT line_items.* from line_items"
+ end
end
def test_should_fail
assert_raise(ArgumentError) do
@@ -33,7 +35,9 @@ end
class HasManyAssociationsTestForCountWithCountSql < ActiveRecord::TestCase
class Invoice < ActiveRecord::Base
- has_many :custom_line_items, :class_name => 'LineItem', :counter_sql => "SELECT COUNT(*) line_items.* from line_items"
+ ActiveSupport::Deprecation.silence do
+ has_many :custom_line_items, :class_name => 'LineItem', :counter_sql => "SELECT COUNT(*) line_items.* from line_items"
+ end
end
def test_should_fail
assert_raise(ArgumentError) do
@@ -44,7 +48,9 @@ end
class HasManyAssociationsTestForCountDistinctWithFinderSql < ActiveRecord::TestCase
class Invoice < ActiveRecord::Base
- has_many :custom_line_items, :class_name => 'LineItem', :finder_sql => "SELECT DISTINCT line_items.amount from line_items"
+ ActiveSupport::Deprecation.silence do
+ has_many :custom_line_items, :class_name => 'LineItem', :finder_sql => "SELECT DISTINCT line_items.amount from line_items"
+ end
end
def test_should_count_distinct_results
@@ -178,7 +184,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
# 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)
- scoped_count = car.foo_bulbs.scoped.where_values.count
+ scoped_count = car.foo_bulbs.where_values.count
bulb = car.foo_bulbs.build
assert_not_equal scoped_count, bulb.scope_after_initialize.where_values.count
@@ -193,7 +199,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_no_sql_should_be_fired_if_association_already_loaded
Car.create(:name => 'honda')
bulbs = Car.first.bulbs
- bulbs.inspect # to load all instances of bulbs
+ bulbs.to_a # to load all instances of bulbs
assert_no_queries do
bulbs.first()
@@ -227,19 +233,19 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
# sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
def test_counting_with_counter_sql
- assert_equal 2, Firm.scoped(:order => "id").first.clients.count
+ assert_equal 2, Firm.all.merge!(:order => "id").first.clients.count
end
def test_counting
- assert_equal 2, Firm.scoped(:order => "id").first.plain_clients.count
+ assert_equal 2, Firm.all.merge!(:order => "id").first.plain_clients.count
end
def test_counting_with_single_hash
- assert_equal 1, Firm.scoped(:order => "id").first.plain_clients.where(:name => "Microsoft").count
+ assert_equal 1, Firm.all.merge!(:order => "id").first.plain_clients.where(:name => "Microsoft").count
end
def test_counting_with_column_name_and_hash
- assert_equal 2, Firm.scoped(:order => "id").first.plain_clients.count(:name)
+ assert_equal 2, Firm.all.merge!(:order => "id").first.plain_clients.count(:name)
end
def test_counting_with_association_limit
@@ -249,7 +255,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_finding
- assert_equal 2, Firm.scoped(:order => "id").first.clients.length
+ assert_equal 2, Firm.all.merge!(:order => "id").first.clients.length
end
def test_finding_array_compatibility
@@ -258,23 +264,23 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_find_with_blank_conditions
[[], {}, nil, ""].each do |blank|
- assert_equal 2, Firm.scoped(:order => "id").first.clients.where(blank).all.size
+ assert_equal 2, Firm.all.merge!(:order => "id").first.clients.where(blank).to_a.size
end
end
def test_find_many_with_merged_options
assert_equal 1, companies(:first_firm).limited_clients.size
- assert_equal 1, companies(:first_firm).limited_clients.all.size
- assert_equal 2, companies(:first_firm).limited_clients.limit(nil).all.size
+ assert_equal 1, companies(:first_firm).limited_clients.to_a.size
+ assert_equal 2, companies(:first_firm).limited_clients.limit(nil).to_a.size
end
- def test_find_should_append_to_association_order
+ def test_find_should_prepend_to_association_order
ordered_clients = companies(:first_firm).clients_sorted_desc.order('companies.id')
- assert_equal ['id DESC', 'companies.id'], ordered_clients.order_values
+ assert_equal ['companies.id', 'id DESC'], ordered_clients.order_values
end
def test_dynamic_find_should_respect_association_order
- assert_equal companies(:second_client), companies(:first_firm).clients_sorted_desc.scoped(:where => "type = 'Client'").first
+ assert_equal companies(:second_client), companies(:first_firm).clients_sorted_desc.where("type = 'Client'").first
assert_equal companies(:second_client), companies(:first_firm).clients_sorted_desc.find_by_type('Client')
end
@@ -284,54 +290,54 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_finding_default_orders
- assert_equal "Summit", Firm.scoped(:order => "id").first.clients.first.name
+ assert_equal "Summit", Firm.all.merge!(:order => "id").first.clients.first.name
end
def test_finding_with_different_class_name_and_order
- assert_equal "Microsoft", Firm.scoped(:order => "id").first.clients_sorted_desc.first.name
+ assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_sorted_desc.first.name
end
def test_finding_with_foreign_key
- assert_equal "Microsoft", Firm.scoped(:order => "id").first.clients_of_firm.first.name
+ assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_of_firm.first.name
end
def test_finding_with_condition
- assert_equal "Microsoft", Firm.scoped(:order => "id").first.clients_like_ms.first.name
+ assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_like_ms.first.name
end
def test_finding_with_condition_hash
- assert_equal "Microsoft", Firm.scoped(:order => "id").first.clients_like_ms_with_hash_conditions.first.name
+ assert_equal "Microsoft", Firm.all.merge!(:order => "id").first.clients_like_ms_with_hash_conditions.first.name
end
def test_finding_using_primary_key
- assert_equal "Summit", Firm.scoped(:order => "id").first.clients_using_primary_key.first.name
+ assert_equal "Summit", Firm.all.merge!(:order => "id").first.clients_using_primary_key.first.name
end
def test_finding_using_sql
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.order("id").first
first_client = firm.clients_using_sql.first
assert_not_nil first_client
assert_equal "Microsoft", first_client.name
assert_equal 1, firm.clients_using_sql.size
- assert_equal 1, Firm.scoped(:order => "id").first.clients_using_sql.size
+ assert_equal 1, Firm.order("id").first.clients_using_sql.size
end
def test_finding_using_sql_take_into_account_only_uniq_ids
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.order("id").first
client = firm.clients_using_sql.first
assert_equal client, firm.clients_using_sql.find(client.id, client.id)
assert_equal client, firm.clients_using_sql.find(client.id, client.id.to_s)
end
def test_counting_using_sql
- assert_equal 1, Firm.scoped(:order => "id").first.clients_using_counter_sql.size
- assert Firm.scoped(:order => "id").first.clients_using_counter_sql.any?
- assert_equal 0, Firm.scoped(:order => "id").first.clients_using_zero_counter_sql.size
- assert !Firm.scoped(:order => "id").first.clients_using_zero_counter_sql.any?
+ assert_equal 1, Firm.order("id").first.clients_using_counter_sql.size
+ assert Firm.order("id").first.clients_using_counter_sql.any?
+ assert_equal 0, Firm.order("id").first.clients_using_zero_counter_sql.size
+ assert !Firm.order("id").first.clients_using_zero_counter_sql.any?
end
def test_counting_non_existant_items_using_sql
- assert_equal 0, Firm.scoped(:order => "id").first.no_clients_using_counter_sql.size
+ assert_equal 0, Firm.order("id").first.no_clients_using_counter_sql.size
end
def test_counting_using_finder_sql
@@ -346,7 +352,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_find_ids
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.all.merge!(:order => "id").first
assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find }
@@ -366,7 +372,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_find_string_ids_when_using_finder_sql
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.order("id").first
client = firm.clients_using_finder_sql.find("2")
assert_kind_of Client, client
@@ -382,9 +388,9 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_find_all
- firm = Firm.scoped(:order => "id").first
- assert_equal 2, firm.clients.scoped(:where => "#{QUOTED_TYPE} = 'Client'").all.length
- assert_equal 1, firm.clients.scoped(:where => "name = 'Summit'").all.length
+ firm = Firm.all.merge!(:order => "id").first
+ assert_equal 2, firm.clients.where("#{QUOTED_TYPE} = 'Client'").to_a.length
+ assert_equal 1, firm.clients.where("name = 'Summit'").to_a.length
end
def test_find_each
@@ -428,29 +434,29 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_find_all_sanitized
# sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
- firm = Firm.scoped(:order => "id").first
- summit = firm.clients.scoped(:where => "name = 'Summit'").all
- assert_equal summit, firm.clients.scoped(:where => ["name = ?", "Summit"]).all
- assert_equal summit, firm.clients.scoped(:where => ["name = :name", { :name => "Summit" }]).all
+ firm = Firm.all.merge!(:order => "id").first
+ summit = firm.clients.where("name = 'Summit'").to_a
+ assert_equal summit, firm.clients.where("name = ?", "Summit").to_a
+ assert_equal summit, firm.clients.where("name = :name", { :name => "Summit" }).to_a
end
def test_find_first
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.all.merge!(:order => "id").first
client2 = Client.find(2)
- assert_equal firm.clients.first, firm.clients.scoped(:order => "id").first
- assert_equal client2, firm.clients.scoped(:where => "#{QUOTED_TYPE} = 'Client'", :order => "id").first
+ assert_equal firm.clients.first, firm.clients.order("id").first
+ assert_equal client2, firm.clients.where("#{QUOTED_TYPE} = 'Client'").order("id").first
end
def test_find_first_sanitized
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.all.merge!(:order => "id").first
client2 = Client.find(2)
- assert_equal client2, firm.clients.scoped(:where => ["#{QUOTED_TYPE} = ?", 'Client'], :order => "id").first
- assert_equal client2, firm.clients.scoped(:where => ["#{QUOTED_TYPE} = :type", { :type => 'Client' }], :order => "id").first
+ assert_equal client2, firm.clients.merge!(:where => ["#{QUOTED_TYPE} = ?", 'Client'], :order => "id").first
+ assert_equal client2, firm.clients.merge!(:where => ["#{QUOTED_TYPE} = :type", { :type => 'Client' }], :order => "id").first
end
def test_find_all_with_include_and_conditions
assert_nothing_raised do
- Developer.scoped(:joins => :audit_logs, :where => {'audit_logs.message' => nil, :name => 'Smith'}).all
+ Developer.all.merge!(:joins => :audit_logs, :where => {'audit_logs.message' => nil, :name => 'Smith'}).to_a
end
end
@@ -460,8 +466,8 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_find_grouped
- all_clients_of_firm1 = Client.scoped(:where => "firm_id = 1").all
- grouped_clients_of_firm1 = Client.scoped(:where => "firm_id = 1", :group => "firm_id", :select => 'firm_id, count(id) as clients_count').all
+ all_clients_of_firm1 = Client.all.merge!(:where => "firm_id = 1").to_a
+ grouped_clients_of_firm1 = Client.all.merge!(:where => "firm_id = 1", :group => "firm_id", :select => 'firm_id, count(id) as clients_count').to_a
assert_equal 2, all_clients_of_firm1.size
assert_equal 1, grouped_clients_of_firm1.size
end
@@ -519,7 +525,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_create_with_bang_on_has_many_raises_when_record_not_saved
assert_raise(ActiveRecord::RecordInvalid) do
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.all.merge!(:order => "id").first
firm.plain_clients.create!
end
end
@@ -718,7 +724,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_deleting_updates_counter_cache_with_dependent_delete_all
post = posts(:welcome)
- post.update_column(:taggings_with_delete_all_count, post.taggings_count)
+ post.update_columns(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)
@@ -727,7 +733,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_deleting_updates_counter_cache_with_dependent_destroy
post = posts(:welcome)
- post.update_column(:taggings_with_destroy_count, post.taggings_count)
+ post.update_columns(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)
@@ -897,7 +903,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
firm = Firm.first
# break the vanilla firm_id foreign key
assert_equal 2, firm.clients.count
- firm.clients.first.update_column(:firm_id, nil)
+ firm.clients.first.update_columns(firm_id: nil)
assert_equal 1, firm.clients(true).count
assert_equal 1, firm.clients_using_primary_key_with_delete_all.count
old_record = firm.clients_using_primary_key_with_delete_all.first
@@ -1023,7 +1029,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
firm = companies(:first_firm)
assert_equal 2, firm.clients.size
firm.destroy
- assert Client.scoped(:where => "firm_id=#{firm.id}").all.empty?
+ assert Client.all.merge!(:where => "firm_id=#{firm.id}").to_a.empty?
end
def test_dependence_for_associations_with_hash_condition
@@ -1033,7 +1039,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_destroy_dependent_when_deleted_from_association
# sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.all.merge!(:order => "id").first
assert_equal 2, firm.clients.size
client = firm.clients.first
@@ -1061,7 +1067,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
firm.destroy rescue "do nothing"
- assert_equal 2, Client.scoped(:where => "firm_id=#{firm.id}").all.size
+ assert_equal 2, Client.all.merge!(:where => "firm_id=#{firm.id}").to_a.size
end
def test_dependence_on_account
@@ -1085,9 +1091,6 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_restrict
- option_before = ActiveRecord::Base.dependent_restrict_raises
- ActiveRecord::Base.dependent_restrict_raises = true
-
firm = RestrictedFirm.create!(:name => 'restrict')
firm.companies.create(:name => 'child')
@@ -1095,15 +1098,25 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
assert RestrictedFirm.exists?(:name => 'restrict')
assert firm.companies.exists?(:name => 'child')
- ensure
- ActiveRecord::Base.dependent_restrict_raises = option_before
end
- def test_restrict_when_dependent_restrict_raises_config_set_to_false
- option_before = ActiveRecord::Base.dependent_restrict_raises
- ActiveRecord::Base.dependent_restrict_raises = false
+ def test_restrict_is_deprecated
+ klass = Class.new(ActiveRecord::Base)
+ assert_deprecated { klass.has_many :posts, dependent: :restrict }
+ end
- firm = RestrictedFirm.create!(:name => 'restrict')
+ def test_restrict_with_exception
+ firm = RestrictedWithExceptionFirm.create!(:name => 'restrict')
+ firm.companies.create(:name => 'child')
+
+ assert !firm.companies.empty?
+ assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
+ assert RestrictedWithExceptionFirm.exists?(:name => 'restrict')
+ assert firm.companies.exists?(:name => 'child')
+ end
+
+ def test_restrict_with_error
+ firm = RestrictedWithErrorFirm.create!(:name => 'restrict')
firm.companies.create(:name => 'child')
assert !firm.companies.empty?
@@ -1113,10 +1126,8 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert !firm.errors.empty?
assert_equal "Cannot delete record because dependent companies exist", firm.errors[:base].first
- assert RestrictedFirm.exists?(:name => 'restrict')
+ assert RestrictedWithErrorFirm.exists?(:name => 'restrict')
assert firm.companies.exists?(:name => 'child')
- ensure
- ActiveRecord::Base.dependent_restrict_raises = option_before
end
def test_included_in_collection
@@ -1128,7 +1139,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_replace_with_less
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.all.merge!(:order => "id").first
firm.clients = [companies(:first_client)]
assert firm.save, "Could not save firm"
firm.reload
@@ -1142,7 +1153,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_replace_with_new
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.all.merge!(:order => "id").first
firm.clients = [companies(:second_client), Client.new("name" => "New Client")]
firm.save
firm.reload
@@ -1242,7 +1253,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_dynamic_find_should_respect_association_order_for_through
- assert_equal Comment.find(10), authors(:david).comments_desc.scoped(:where => "comments.type = 'SpecialComment'").first
+ assert_equal Comment.find(10), authors(:david).comments_desc.where("comments.type = 'SpecialComment'").first
assert_equal Comment.find(10), authors(:david).comments_desc.find_by_type('SpecialComment')
end
@@ -1358,7 +1369,6 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
assert_equal author.essays, Essay.where(writer_id: "David")
-
end
def test_has_many_custom_primary_key
@@ -1432,13 +1442,12 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
firm = Namespaced::Firm.create({ :name => 'Some Company' })
firm.clients.create({ :name => 'Some Client' })
- stats = Namespaced::Firm.scoped(
+ stats = Namespaced::Firm.all.merge!(
:select => "#{Namespaced::Firm.table_name}.id, COUNT(#{Namespaced::Client.table_name}.id) AS num_clients",
:joins => :clients,
:group => "#{Namespaced::Firm.table_name}.id"
).find firm.id
assert_equal 1, stats.num_clients.to_i
-
ensure
ActiveRecord::Base.store_full_sti_class = old
end
@@ -1462,14 +1471,14 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
end
def test_creating_using_primary_key
- firm = Firm.scoped(:order => "id").first
+ firm = Firm.all.merge!(:order => "id").first
client = firm.clients_using_primary_key.create!(:name => 'test')
assert_equal firm.name, client.firm_name
end
def test_defining_has_many_association_with_delete_all_dependency_lazily_evaluates_target_class
ActiveRecord::Reflection::AssociationReflection.any_instance.expects(:class_name).never
- class_eval <<-EOF
+ class_eval(<<-EOF, __FILE__, __LINE__ + 1)
class DeleteAllModel < ActiveRecord::Base
has_many :nonentities, :dependent => :delete_all
end
@@ -1478,7 +1487,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
def test_defining_has_many_association_with_nullify_dependency_lazily_evaluates_target_class
ActiveRecord::Reflection::AssociationReflection.any_instance.expects(:class_name).never
- class_eval <<-EOF
+ class_eval(<<-EOF, __FILE__, __LINE__ + 1)
class NullifyModel < ActiveRecord::Base
has_many :nonentities, :dependent => :nullify
end
@@ -1598,18 +1607,6 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert_equal [bulb1, bulb3], result
end
- def test_building_has_many_association_with_restrict_dependency
- option_before = ActiveRecord::Base.dependent_restrict_raises
- ActiveRecord::Base.dependent_restrict_raises = true
-
- klass = Class.new(ActiveRecord::Base)
-
- assert_deprecated { klass.has_many :companies, :dependent => :restrict }
- assert_not_deprecated { klass.has_many :companies }
- ensure
- ActiveRecord::Base.dependent_restrict_raises = option_before
- end
-
def test_collection_association_with_private_kernel_method
firm = companies(:first_firm)
assert_equal [accounts(:signals37)], firm.accounts.open
@@ -1640,4 +1637,14 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
post.taggings_with_delete_all.delete_all
end
end
+
+ test ":finder_sql is deprecated" do
+ klass = Class.new(ActiveRecord::Base)
+ assert_deprecated { klass.has_many :foo, :finder_sql => 'lol' }
+ end
+
+ test ":counter_sql is deprecated" do
+ klass = Class.new(ActiveRecord::Base)
+ assert_deprecated { klass.has_many :foo, :counter_sql => 'lol' }
+ 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 1c06007d86..36e5ba9660 100644
--- a/activerecord/test/cases/associations/has_many_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb
@@ -327,7 +327,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
def test_update_counter_caches_on_delete_with_dependent_destroy
post = posts(:welcome)
tag = post.tags.create!(:name => 'doomed')
- post.update_column(:tags_with_destroy_count, post.tags.count)
+ post.update_columns(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)
@@ -337,7 +337,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
def test_update_counter_caches_on_delete_with_dependent_nullify
post = posts(:welcome)
tag = post.tags.create!(:name => 'doomed')
- post.update_column(:tags_with_nullify_count, post.tags.count)
+ post.update_columns(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
@@ -706,7 +706,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
def test_through_association_readonly_should_be_false
assert !people(:michael).posts.first.readonly?
- assert !people(:michael).posts.all.first.readonly?
+ assert !people(:michael).posts.to_a.first.readonly?
end
def test_can_update_through_association
@@ -742,7 +742,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
end
def test_has_many_through_with_default_scope_on_join_model
- assert_equal posts(:welcome).comments.order('id').all, authors(:david).comments_on_first_posts
+ assert_equal posts(:welcome).comments.order('id').to_a, authors(:david).comments_on_first_posts
end
def test_create_has_many_through_with_default_scope_on_join_model
@@ -813,13 +813,6 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
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
-
def test_primary_key_option_on_source
post = posts(:welcome)
category = categories(:general)
diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb
index 88ec65706c..8bc633f2b5 100644
--- a/activerecord/test/cases/associations/has_one_associations_test.rb
+++ b/activerecord/test/cases/associations/has_one_associations_test.rb
@@ -25,13 +25,13 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
assert_queries(1) { assert_nil firm.account }
assert_queries(0) { assert_nil firm.account }
- firms = Firm.scoped(:includes => :account).all
+ firms = Firm.all.merge!(:includes => :account).to_a
assert_queries(0) { firms.each(&:account) }
end
def test_with_select
assert_equal Firm.find(1).account_with_select.attributes.size, 2
- assert_equal Firm.scoped(:includes => :account_with_select).find(1).account_with_select.attributes.size, 2
+ assert_equal Firm.all.merge!(:includes => :account_with_select).find(1).account_with_select.attributes.size, 2
end
def test_finding_using_primary_key
@@ -156,10 +156,7 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
assert_nothing_raised { firm.destroy }
end
- def test_dependence_with_restrict
- option_before = ActiveRecord::Base.dependent_restrict_raises
- ActiveRecord::Base.dependent_restrict_raises = true
-
+ def test_restrict
firm = RestrictedFirm.create!(:name => 'restrict')
firm.create_account(:credit_limit => 10)
@@ -168,38 +165,26 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
assert RestrictedFirm.exists?(:name => 'restrict')
assert firm.account.present?
- ensure
- ActiveRecord::Base.dependent_restrict_raises = option_before
end
- def test_dependence_with_restrict_with_dependent_restrict_raises_config_set_to_false
- option_before = ActiveRecord::Base.dependent_restrict_raises
- ActiveRecord::Base.dependent_restrict_raises = false
+ def test_restrict_is_deprecated
+ klass = Class.new(ActiveRecord::Base)
+ assert_deprecated { klass.has_one :post, dependent: :restrict }
+ end
- firm = RestrictedFirm.create!(:name => 'restrict')
+ def test_restrict_with_exception
+ firm = RestrictedWithExceptionFirm.create!(:name => 'restrict')
firm.create_account(:credit_limit => 10)
assert_not_nil firm.account
- firm.destroy
-
- assert !firm.errors.empty?
- assert_equal "Cannot delete record because a dependent account exists", firm.errors[:base].first
- assert RestrictedFirm.exists?(:name => 'restrict')
+ assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
+ assert RestrictedWithExceptionFirm.exists?(:name => 'restrict')
assert firm.account.present?
- ensure
- ActiveRecord::Base.dependent_restrict_raises = option_before
end
- def test_dependence_with_restrict_with_dependent_restrict_raises_config_set_to_false_and_attribute_name
- old_backend = I18n.backend
- I18n.backend = I18n::Backend::Simple.new
- I18n.backend.store_translations 'en', :activerecord => {:attributes => {:restricted_firm => {:account => "account model"}}}
-
- option_before = ActiveRecord::Base.dependent_restrict_raises
- ActiveRecord::Base.dependent_restrict_raises = false
-
- firm = RestrictedFirm.create!(:name => 'restrict')
+ def test_restrict_with_error
+ firm = RestrictedWithErrorFirm.create!(:name => 'restrict')
firm.create_account(:credit_limit => 10)
assert_not_nil firm.account
@@ -207,12 +192,9 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
firm.destroy
assert !firm.errors.empty?
- assert_equal "Cannot delete record because a dependent account model exists", firm.errors[:base].first
- assert RestrictedFirm.exists?(:name => 'restrict')
+ assert_equal "Cannot delete record because a dependent account exists", firm.errors[:base].first
+ assert RestrictedWithErrorFirm.exists?(:name => 'restrict')
assert firm.account.present?
- ensure
- ActiveRecord::Base.dependent_restrict_raises = option_before
- I18n.backend = old_backend
end
def test_successful_build_association
@@ -226,7 +208,7 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
def test_build_and_create_should_not_happen_within_scope
pirate = pirates(:blackbeard)
- scoped_count = pirate.association(:foo_bulb).scoped.where_values.count
+ scoped_count = pirate.association(:foo_bulb).scope.where_values.count
bulb = pirate.build_foo_bulb
assert_not_equal scoped_count, bulb.scope_after_initialize.where_values.count
@@ -346,14 +328,14 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
assert_nothing_raised do
Firm.find(@firm.id).save!
- Firm.scoped(:includes => :account).find(@firm.id).save!
+ Firm.all.merge!(:includes => :account).find(@firm.id).save!
end
@firm.account.destroy
assert_nothing_raised do
Firm.find(@firm.id).save!
- Firm.scoped(:includes => :account).find(@firm.id).save!
+ Firm.all.merge!(:includes => :account).find(@firm.id).save!
end
end
@@ -524,15 +506,16 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
assert_equal car.id, bulb.attributes_after_initialize['car_id']
end
- def test_building_has_one_association_with_dependent_restrict
- option_before = ActiveRecord::Base.dependent_restrict_raises
- ActiveRecord::Base.dependent_restrict_raises = true
+ def test_has_one_transaction
+ company = companies(:first_firm)
+ account = Account.find(1)
- klass = Class.new(ActiveRecord::Base)
+ company.account # force loading
+ assert_no_queries { company.account = account }
- assert_deprecated { klass.has_one :account, :dependent => :restrict }
- assert_not_deprecated { klass.has_one :account }
- ensure
- ActiveRecord::Base.dependent_restrict_raises = option_before
+ company.account = nil
+ assert_no_queries { company.account = nil }
+ account = Account.find(2)
+ assert_queries { company.account = account }
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 94b9639e57..90c557e886 100644
--- a/activerecord/test/cases/associations/has_one_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb
@@ -73,7 +73,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
def test_has_one_through_eager_loading
members = assert_queries(3) do #base table, through table, clubs table
- Member.scoped(:includes => :club, :where => ["name = ?", "Groucho Marx"]).all
+ Member.all.merge!(:includes => :club, :where => ["name = ?", "Groucho Marx"]).to_a
end
assert_equal 1, members.size
assert_not_nil assert_no_queries {members[0].club}
@@ -81,7 +81,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
def test_has_one_through_eager_loading_through_polymorphic
members = assert_queries(3) do #base table, through table, clubs table
- Member.scoped(:includes => :sponsor_club, :where => ["name = ?", "Groucho Marx"]).all
+ Member.all.merge!(:includes => :sponsor_club, :where => ["name = ?", "Groucho Marx"]).to_a
end
assert_equal 1, members.size
assert_not_nil assert_no_queries {members[0].sponsor_club}
@@ -89,14 +89,14 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
def test_has_one_through_with_conditions_eager_loading
# conditions on the through table
- assert_equal clubs(:moustache_club), Member.scoped(:includes => :favourite_club).find(@member.id).favourite_club
- memberships(:membership_of_favourite_club).update_column(:favourite, false)
- assert_equal nil, Member.scoped(:includes => :favourite_club).find(@member.id).reload.favourite_club
+ assert_equal clubs(:moustache_club), Member.all.merge!(:includes => :favourite_club).find(@member.id).favourite_club
+ memberships(:membership_of_favourite_club).update_columns(favourite: false)
+ assert_equal nil, Member.all.merge!(:includes => :favourite_club).find(@member.id).reload.favourite_club
# conditions on the source table
- assert_equal clubs(:moustache_club), Member.scoped(:includes => :hairy_club).find(@member.id).hairy_club
- clubs(:moustache_club).update_column(:name, "Association of Clean-Shaven Persons")
- assert_equal nil, Member.scoped(:includes => :hairy_club).find(@member.id).reload.hairy_club
+ assert_equal clubs(:moustache_club), Member.all.merge!(:includes => :hairy_club).find(@member.id).hairy_club
+ clubs(:moustache_club).update_columns(name: "Association of Clean-Shaven Persons")
+ assert_equal nil, Member.all.merge!(:includes => :hairy_club).find(@member.id).reload.hairy_club
end
def test_has_one_through_polymorphic_with_source_type
@@ -104,14 +104,14 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
end
def test_eager_has_one_through_polymorphic_with_source_type
- clubs = Club.scoped(:includes => :sponsored_member, :where => ["name = ?","Moustache and Eyebrow Fancier Club"]).all
+ clubs = Club.all.merge!(:includes => :sponsored_member, :where => ["name = ?","Moustache and Eyebrow Fancier Club"]).to_a
# Only the eyebrow fanciers club has a sponsored_member
assert_not_nil assert_no_queries {clubs[0].sponsored_member}
end
def test_has_one_through_nonpreload_eagerloading
members = assert_queries(1) do
- Member.scoped(:includes => :club, :where => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name').all #force fallback
+ Member.all.merge!(:includes => :club, :where => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name').to_a #force fallback
end
assert_equal 1, members.size
assert_not_nil assert_no_queries {members[0].club}
@@ -119,7 +119,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
def test_has_one_through_nonpreload_eager_loading_through_polymorphic
members = assert_queries(1) do
- Member.scoped(:includes => :sponsor_club, :where => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name').all #force fallback
+ Member.all.merge!(:includes => :sponsor_club, :where => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name').to_a #force fallback
end
assert_equal 1, members.size
assert_not_nil assert_no_queries {members[0].sponsor_club}
@@ -128,7 +128,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
def test_has_one_through_nonpreload_eager_loading_through_polymorphic_with_more_than_one_through_record
Sponsor.new(:sponsor_club => clubs(:crazy_club), :sponsorable => members(:groucho)).save!
members = assert_queries(1) do
- Member.scoped(:includes => :sponsor_club, :where => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name DESC').all #force fallback
+ Member.all.merge!(:includes => :sponsor_club, :where => ["members.name = ?", "Groucho Marx"], :order => 'clubs.name DESC').to_a #force fallback
end
assert_equal 1, members.size
assert_not_nil assert_no_queries { members[0].sponsor_club }
@@ -197,7 +197,7 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
@member.member_detail = @member_detail
@member.organization = @organization
@member_details = assert_queries(3) do
- MemberDetail.scoped(:includes => :member_type).all
+ MemberDetail.all.merge!(:includes => :member_type).to_a
end
@new_detail = @member_details[0]
assert @new_detail.send(:association, :member_type).loaded?
@@ -210,14 +210,14 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase
assert_nothing_raised do
Club.find(@club.id).save!
- Club.scoped(:includes => :sponsored_member).find(@club.id).save!
+ Club.all.merge!(:includes => :sponsored_member).find(@club.id).save!
end
@club.sponsor.destroy
assert_nothing_raised do
Club.find(@club.id).save!
- Club.scoped(:includes => :sponsored_member).find(@club.id).save!
+ Club.all.merge!(:includes => :sponsored_member).find(@club.id).save!
end
end
diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb
index 1d61d5c474..4f246f575e 100644
--- a/activerecord/test/cases/associations/inner_join_association_test.rb
+++ b/activerecord/test/cases/associations/inner_join_association_test.rb
@@ -71,18 +71,18 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase
end
def test_count_honors_implicit_inner_joins
- real_count = Author.scoped.to_a.sum{|a| a.posts.count }
+ real_count = Author.all.to_a.sum{|a| a.posts.count }
assert_equal real_count, Author.joins(:posts).count, "plain inner join count should match the number of referenced posts records"
end
def test_calculate_honors_implicit_inner_joins
- real_count = Author.scoped.to_a.sum{|a| a.posts.count }
+ real_count = Author.all.to_a.sum{|a| a.posts.count }
assert_equal real_count, Author.joins(:posts).calculate(:count, 'authors.id'), "plain inner join count should match the number of referenced posts records"
end
def test_calculate_honors_implicit_inner_joins_and_distinct_and_conditions
- real_count = Author.scoped.to_a.select {|a| a.posts.any? {|p| p.title =~ /^Welcome/} }.length
- authors_with_welcoming_post_titles = Author.scoped(:joins => :posts, :where => "posts.title like 'Welcome%'").calculate(:count, 'authors.id', :distinct => true)
+ real_count = Author.all.to_a.select {|a| a.posts.any? {|p| p.title =~ /^Welcome/} }.length
+ authors_with_welcoming_post_titles = Author.all.merge!(:joins => :posts, :where => "posts.title like 'Welcome%'").calculate(:count, 'authors.id', :distinct => true)
assert_equal real_count, authors_with_welcoming_post_titles, "inner join and conditions should have only returned authors posting titles starting with 'Welcome'"
end
diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb
index f35ffb2994..aad48e7ce9 100644
--- a/activerecord/test/cases/associations/inverse_associations_test.rb
+++ b/activerecord/test/cases/associations/inverse_associations_test.rb
@@ -96,7 +96,7 @@ class InverseHasOneTests < ActiveRecord::TestCase
def test_parent_instance_should_be_shared_with_eager_loaded_child_on_find
- m = Man.scoped(:where => {:name => 'Gordon'}, :includes => :face).first
+ m = Man.all.merge!(:where => {:name => 'Gordon'}, :includes => :face).first
f = m.face
assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
m.name = 'Bongo'
@@ -104,7 +104,7 @@ class InverseHasOneTests < ActiveRecord::TestCase
f.man.name = 'Mungo'
assert_equal m.name, f.man.name, "Name of man should be the same after changes to child-owned instance"
- m = Man.scoped(:where => {:name => 'Gordon'}, :includes => :face, :order => 'faces.id').first
+ m = Man.all.merge!(:where => {:name => 'Gordon'}, :includes => :face, :order => 'faces.id').first
f = m.face
assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
m.name = 'Bongo'
@@ -179,7 +179,7 @@ class InverseHasManyTests < ActiveRecord::TestCase
end
def test_parent_instance_should_be_shared_with_eager_loaded_children
- m = Man.scoped(:where => {:name => 'Gordon'}, :includes => :interests).first
+ m = Man.all.merge!(:where => {:name => 'Gordon'}, :includes => :interests).first
is = m.interests
is.each do |i|
assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
@@ -189,7 +189,7 @@ class InverseHasManyTests < ActiveRecord::TestCase
assert_equal m.name, i.man.name, "Name of man should be the same after changes to child-owned instance"
end
- m = Man.scoped(:where => {:name => 'Gordon'}, :includes => :interests, :order => 'interests.id').first
+ m = Man.all.merge!(:where => {:name => 'Gordon'}, :includes => :interests, :order => 'interests.id').first
is = m.interests
is.each do |i|
assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
@@ -259,6 +259,12 @@ 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_first_and_last_child
+ man = Man.first
+ assert man.interests.first.man.equal? man
+ assert man.interests.last.man.equal? man
+ end
+
def test_trying_to_use_inverses_that_dont_exist_should_raise_an_error
assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { Man.first.secret_interests }
end
@@ -278,7 +284,7 @@ class InverseBelongsToTests < ActiveRecord::TestCase
end
def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find
- f = Face.scoped(:includes => :man, :where => {:description => 'trusting'}).first
+ f = Face.all.merge!(:includes => :man, :where => {:description => 'trusting'}).first
m = f.man
assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
f.description = 'gormless'
@@ -286,7 +292,7 @@ class InverseBelongsToTests < ActiveRecord::TestCase
m.face.description = 'pleasing'
assert_equal f.description, m.face.description, "Description of face should be the same after changes to parent-owned instance"
- f = Face.scoped(:includes => :man, :order => 'men.id', :where => {:description => 'trusting'}).first
+ f = Face.all.merge!(:includes => :man, :order => 'men.id', :where => {:description => 'trusting'}).first
m = f.man
assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
f.description = 'gormless'
@@ -351,7 +357,7 @@ class InversePolymorphicBelongsToTests < ActiveRecord::TestCase
fixtures :men, :faces, :interests
def test_child_instance_should_be_shared_with_parent_on_find
- f = Face.scoped(:where => {:description => 'confused'}).first
+ f = Face.all.merge!(:where => {:description => 'confused'}).first
m = f.polymorphic_man
assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same before changes to child instance"
f.description = 'gormless'
@@ -361,7 +367,7 @@ class InversePolymorphicBelongsToTests < ActiveRecord::TestCase
end
def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find
- f = Face.scoped(:where => {:description => 'confused'}, :includes => :man).first
+ f = Face.all.merge!(:where => {:description => 'confused'}, :includes => :man).first
m = f.polymorphic_man
assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same before changes to child instance"
f.description = 'gormless'
@@ -369,7 +375,7 @@ class InversePolymorphicBelongsToTests < ActiveRecord::TestCase
m.polymorphic_face.description = 'pleasing'
assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to parent-owned instance"
- f = Face.scoped(:where => {:description => 'confused'}, :includes => :man, :order => 'men.id').first
+ f = Face.all.merge!(:where => {:description => 'confused'}, :includes => :man, :order => 'men.id').first
m = f.polymorphic_man
assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same before changes to child instance"
f.description = 'gormless'
diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb
index 783b83631c..86893ec4b3 100644
--- a/activerecord/test/cases/associations/join_model_test.rb
+++ b/activerecord/test/cases/associations/join_model_test.rb
@@ -1,5 +1,4 @@
require "cases/helper"
-require 'active_support/core_ext/object/inclusion'
require 'models/tag'
require 'models/tagging'
require 'models/post'
@@ -51,7 +50,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_has_many_uniq_through_find
- assert_equal 1, authors(:mary).unique_categorized_posts.all.size
+ assert_equal 1, authors(:mary).unique_categorized_posts.to_a.size
end
def test_polymorphic_has_many_going_through_join_model
@@ -175,7 +174,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_delete_polymorphic_has_many_with_delete_all
assert_equal 1, posts(:welcome).taggings.count
- posts(:welcome).taggings.first.update_column :taggable_type, 'PostWithHasManyDeleteAll'
+ posts(:welcome).taggings.first.update_columns taggable_type: 'PostWithHasManyDeleteAll'
post = find_post_with_dependency(1, :has_many, :taggings, :delete_all)
old_count = Tagging.count
@@ -186,7 +185,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_delete_polymorphic_has_many_with_destroy
assert_equal 1, posts(:welcome).taggings.count
- posts(:welcome).taggings.first.update_column :taggable_type, 'PostWithHasManyDestroy'
+ posts(:welcome).taggings.first.update_columns taggable_type: 'PostWithHasManyDestroy'
post = find_post_with_dependency(1, :has_many, :taggings, :destroy)
old_count = Tagging.count
@@ -197,7 +196,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_delete_polymorphic_has_many_with_nullify
assert_equal 1, posts(:welcome).taggings.count
- posts(:welcome).taggings.first.update_column :taggable_type, 'PostWithHasManyNullify'
+ posts(:welcome).taggings.first.update_columns taggable_type: 'PostWithHasManyNullify'
post = find_post_with_dependency(1, :has_many, :taggings, :nullify)
old_count = Tagging.count
@@ -208,7 +207,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_delete_polymorphic_has_one_with_destroy
assert posts(:welcome).tagging
- posts(:welcome).tagging.update_column :taggable_type, 'PostWithHasOneDestroy'
+ posts(:welcome).tagging.update_columns taggable_type: 'PostWithHasOneDestroy'
post = find_post_with_dependency(1, :has_one, :tagging, :destroy)
old_count = Tagging.count
@@ -219,7 +218,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_delete_polymorphic_has_one_with_nullify
assert posts(:welcome).tagging
- posts(:welcome).tagging.update_column :taggable_type, 'PostWithHasOneNullify'
+ posts(:welcome).tagging.update_columns taggable_type: 'PostWithHasOneNullify'
post = find_post_with_dependency(1, :has_one, :tagging, :nullify)
old_count = Tagging.count
@@ -233,8 +232,8 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_include_has_many_through
- posts = Post.scoped(:order => 'posts.id').all
- posts_with_authors = Post.scoped(:includes => :authors, :order => 'posts.id').all
+ posts = Post.all.merge!(:order => 'posts.id').to_a
+ posts_with_authors = Post.all.merge!(:includes => :authors, :order => 'posts.id').to_a
assert_equal posts.length, posts_with_authors.length
posts.length.times do |i|
assert_equal posts[i].authors.length, assert_no_queries { posts_with_authors[i].authors.length }
@@ -258,8 +257,8 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_include_polymorphic_has_many_through
- posts = Post.scoped(:order => 'posts.id').all
- posts_with_tags = Post.scoped(:includes => :tags, :order => 'posts.id').all
+ posts = Post.all.merge!(:order => 'posts.id').to_a
+ posts_with_tags = Post.all.merge!(:includes => :tags, :order => 'posts.id').to_a
assert_equal posts.length, posts_with_tags.length
posts.length.times do |i|
assert_equal posts[i].tags.length, assert_no_queries { posts_with_tags[i].tags.length }
@@ -267,8 +266,8 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_include_polymorphic_has_many
- posts = Post.scoped(:order => 'posts.id').all
- posts_with_taggings = Post.scoped(:includes => :taggings, :order => 'posts.id').all
+ posts = Post.all.merge!(:order => 'posts.id').to_a
+ posts_with_taggings = Post.all.merge!(:includes => :taggings, :order => 'posts.id').to_a
assert_equal posts.length, posts_with_taggings.length
posts.length.times do |i|
assert_equal posts[i].taggings.length, assert_no_queries { posts_with_taggings[i].taggings.length }
@@ -276,7 +275,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_has_many_find_all
- assert_equal [categories(:general)], authors(:david).categories.all
+ assert_equal [categories(:general)], authors(:david).categories.to_a
end
def test_has_many_find_first
@@ -288,8 +287,8 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_has_many_find_conditions
- assert_equal categories(:general), authors(:david).categories.scoped(:where => "categories.name = 'General'").first
- assert_nil authors(:david).categories.scoped(:where => "categories.name = 'Technology'").first
+ assert_equal categories(:general), authors(:david).categories.where("categories.name = 'General'").first
+ assert_nil authors(:david).categories.where("categories.name = 'Technology'").first
end
def test_has_many_array_methods_called_by_method_missing
@@ -355,7 +354,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_eager_has_many_polymorphic_with_source_type
- tag_with_include = Tag.scoped(:includes => :tagged_posts).find(tags(:general).id)
+ tag_with_include = Tag.all.merge!(:includes => :tagged_posts).find(tags(:general).id)
desired = posts(:welcome, :thinking)
assert_no_queries do
# added sort by ID as otherwise test using JRuby was failing as array elements were in different order
@@ -365,20 +364,20 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_has_many_through_has_many_find_all
- assert_equal comments(:greetings), authors(:david).comments.scoped(:order => 'comments.id').all.first
+ assert_equal comments(:greetings), authors(:david).comments.order('comments.id').to_a.first
end
def test_has_many_through_has_many_find_all_with_custom_class
- assert_equal comments(:greetings), authors(:david).funky_comments.scoped(:order => 'comments.id').all.first
+ assert_equal comments(:greetings), authors(:david).funky_comments.order('comments.id').to_a.first
end
def test_has_many_through_has_many_find_first
- assert_equal comments(:greetings), authors(:david).comments.scoped(:order => 'comments.id').first
+ assert_equal comments(:greetings), authors(:david).comments.order('comments.id').first
end
def test_has_many_through_has_many_find_conditions
options = { :where => "comments.#{QUOTED_TYPE}='SpecialComment'", :order => 'comments.id' }
- assert_equal comments(:does_it_hurt), authors(:david).comments.scoped(options).first
+ assert_equal comments(:does_it_hurt), authors(:david).comments.merge(options).first
end
def test_has_many_through_has_many_find_by_id
@@ -386,7 +385,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_has_many_through_polymorphic_has_one
- assert_equal Tagging.find(1,2).sort_by { |t| t.id }, authors(:david).tagging
+ assert_equal Tagging.find(1,2).sort_by { |t| t.id }, authors(:david).taggings_2
end
def test_has_many_through_polymorphic_has_many
@@ -402,7 +401,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_eager_load_has_many_through_has_many
- author = Author.scoped(:where => ['name = ?', 'David'], :includes => :comments, :order => 'comments.id').first
+ author = Author.all.merge!(:where => ['name = ?', 'David'], :includes => :comments, :order => 'comments.id').first
SpecialComment.new; VerySpecialComment.new
assert_no_queries do
assert_equal [1,2,3,5,6,7,8,9,10,12], author.comments.collect(&:id)
@@ -410,7 +409,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_eager_load_has_many_through_has_many_with_conditions
- post = Post.scoped(:includes => :invalid_tags).first
+ post = Post.all.merge!(:includes => :invalid_tags).first
assert_no_queries do
post.invalid_tags
end
@@ -418,8 +417,8 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_eager_belongs_to_and_has_one_not_singularized
assert_nothing_raised do
- Author.scoped(:includes => :author_address).first
- AuthorAddress.scoped(:includes => :author).first
+ Author.all.merge!(:includes => :author_address).first
+ AuthorAddress.all.merge!(:includes => :author).first
end
end
@@ -454,7 +453,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
assert saved_post.tags.include?(new_tag)
assert new_tag.persisted?
- assert new_tag.in?(saved_post.reload.tags(true))
+ assert saved_post.reload.tags(true).include?(new_tag)
new_post = Post.new(:title => "Association replacmenet works!", :body => "You best believe it.")
@@ -467,7 +466,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
new_post.save!
assert new_post.persisted?
- assert saved_tag.in?(new_post.reload.tags(true))
+ assert new_post.reload.tags(true).include?(saved_tag)
assert !posts(:thinking).tags.build.persisted?
assert !posts(:thinking).tags.new.persisted?
@@ -625,7 +624,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_polymorphic_has_many
expected = taggings(:welcome_general)
- p = Post.scoped(:includes => :taggings).find(posts(:welcome).id)
+ p = Post.all.merge!(:includes => :taggings).find(posts(:welcome).id)
assert_no_queries {assert p.taggings.include?(expected)}
assert posts(:welcome).taggings.include?(taggings(:welcome_general))
end
@@ -633,18 +632,18 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_polymorphic_has_one
expected = posts(:welcome)
- tagging = Tagging.scoped(:includes => :taggable).find(taggings(:welcome_general).id)
+ tagging = Tagging.all.merge!(:includes => :taggable).find(taggings(:welcome_general).id)
assert_no_queries { assert_equal expected, tagging.taggable}
end
def test_polymorphic_belongs_to
- p = Post.scoped(:includes => {:taggings => :taggable}).find(posts(:welcome).id)
+ p = Post.all.merge!(:includes => {:taggings => :taggable}).find(posts(:welcome).id)
assert_no_queries {assert_equal posts(:welcome), p.taggings.first.taggable}
end
def test_preload_polymorphic_has_many_through
- posts = Post.scoped(:order => 'posts.id').all
- posts_with_tags = Post.scoped(:includes => :tags, :order => 'posts.id').all
+ posts = Post.all.merge!(:order => 'posts.id').to_a
+ posts_with_tags = Post.all.merge!(:includes => :tags, :order => 'posts.id').to_a
assert_equal posts.length, posts_with_tags.length
posts.length.times do |i|
assert_equal posts[i].tags.length, assert_no_queries { posts_with_tags[i].tags.length }
@@ -652,7 +651,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_preload_polymorph_many_types
- taggings = Tagging.scoped(:includes => :taggable, :where => ['taggable_type != ?', 'FakeModel']).all
+ taggings = Tagging.all.merge!(:includes => :taggable, :where => ['taggable_type != ?', 'FakeModel']).to_a
assert_no_queries do
taggings.first.taggable.id
taggings[1].taggable.id
@@ -665,13 +664,13 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
def test_preload_nil_polymorphic_belongs_to
assert_nothing_raised do
- Tagging.scoped(:includes => :taggable, :where => ['taggable_type IS NULL']).all
+ Tagging.all.merge!(:includes => :taggable, :where => ['taggable_type IS NULL']).to_a
end
end
def test_preload_polymorphic_has_many
- posts = Post.scoped(:order => 'posts.id').all
- posts_with_taggings = Post.scoped(:includes => :taggings, :order => 'posts.id').all
+ posts = Post.all.merge!(:order => 'posts.id').to_a
+ posts_with_taggings = Post.all.merge!(:includes => :taggings, :order => 'posts.id').to_a
assert_equal posts.length, posts_with_taggings.length
posts.length.times do |i|
assert_equal posts[i].taggings.length, assert_no_queries { posts_with_taggings[i].taggings.length }
@@ -679,7 +678,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
end
def test_belongs_to_shared_parent
- comments = Comment.scoped(:includes => :post, :where => 'post_id = 1').all
+ comments = Comment.all.merge!(:includes => :post, :where => 'post_id = 1').to_a
assert_no_queries do
assert_equal comments.first.post, comments[1].post
end
@@ -734,7 +733,7 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase
# create dynamic Post models to allow different dependency options
def find_post_with_dependency(post_id, association, association_name, dependency)
class_name = "PostWith#{association.to_s.classify}#{dependency.to_s.classify}"
- Post.find(post_id).update_column :type, class_name
+ Post.find(post_id).update_columns type: class_name
klass = Object.const_set(class_name, Class.new(ActiveRecord::Base))
klass.table_name = 'posts'
klass.send(association, association_name, :as => :taggable, :dependent => dependency)
diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb
index 1d0550afaf..c0f1945cec 100644
--- a/activerecord/test/cases/associations_test.rb
+++ b/activerecord/test/cases/associations_test.rb
@@ -67,15 +67,15 @@ class AssociationsTest < ActiveRecord::TestCase
ship = Ship.create!(:name => "The good ship Dollypop")
part = ship.parts.create!(:name => "Mast")
part.mark_for_destruction
- ShipPart.find(part.id).update_column(:name, 'Deck')
+ ShipPart.find(part.id).update_columns(name: 'Deck')
ship.parts.send(:load_target)
assert_equal 'Deck', ship.parts[0].name
end
def test_include_with_order_works
- assert_nothing_raised {Account.scoped(:order => 'id', :includes => :firm).first}
- assert_nothing_raised {Account.scoped(:order => :id, :includes => :firm).first}
+ assert_nothing_raised {Account.all.merge!(:order => 'id', :includes => :firm).first}
+ assert_nothing_raised {Account.all.merge!(:order => :id, :includes => :firm).first}
end
def test_bad_collection_keys
@@ -86,7 +86,7 @@ class AssociationsTest < ActiveRecord::TestCase
def test_should_construct_new_finder_sql_after_create
person = Person.new :first_name => 'clark'
- assert_equal [], person.readers.all
+ assert_equal [], person.readers.to_a
person.save!
reader = Reader.create! :person => person, :post => Post.new(:title => "foo", :body => "bar")
assert person.readers.find(reader.id)
@@ -110,7 +110,7 @@ class AssociationsTest < ActiveRecord::TestCase
end
def test_using_limitable_reflections_helper
- using_limitable_reflections = lambda { |reflections| Tagging.scoped.send :using_limitable_reflections?, reflections }
+ using_limitable_reflections = lambda { |reflections| Tagging.all.send :using_limitable_reflections?, reflections }
belongs_to_reflections = [Tagging.reflect_on_association(:tag), Tagging.reflect_on_association(:super_tag)]
has_many_reflections = [Tag.reflect_on_association(:taggings), Developer.reflect_on_association(:projects)]
mixed_reflections = (belongs_to_reflections + has_many_reflections).uniq
@@ -131,7 +131,7 @@ class AssociationsTest < ActiveRecord::TestCase
def test_association_with_references
firm = companies(:first_firm)
- assert_equal ['foo'], firm.association_with_references.scoped.references_values
+ assert_equal ['foo'], firm.association_with_references.references_values
end
end
@@ -176,7 +176,7 @@ class AssociationProxyTest < ActiveRecord::TestCase
david = developers(:david)
assert !david.projects.loaded?
- david.update_column(:created_at, Time.now)
+ david.update_columns(created_at: Time.now)
assert !david.projects.loaded?
end
@@ -216,7 +216,14 @@ class AssociationProxyTest < ActiveRecord::TestCase
end
def test_scoped_allows_conditions
- assert developers(:david).projects.scoped(where: 'foo').where_values.include?('foo')
+ assert developers(:david).projects.merge!(where: 'foo').where_values.include?('foo')
+ end
+
+ test "getting a scope from an association" do
+ david = developers(:david)
+
+ assert david.projects.scope.is_a?(ActiveRecord::Relation)
+ assert_equal david.projects, david.projects.scope
end
end
diff --git a/activerecord/test/cases/attribute_methods/read_test.rb b/activerecord/test/cases/attribute_methods/read_test.rb
index 98c38535a6..da5d9d8c2a 100644
--- a/activerecord/test/cases/attribute_methods/read_test.rb
+++ b/activerecord/test/cases/attribute_methods/read_test.rb
@@ -1,5 +1,4 @@
require "cases/helper"
-require 'active_support/core_ext/object/inclusion'
require 'thread'
module ActiveRecord
@@ -15,6 +14,7 @@ module ActiveRecord
def self.active_record_super; Base; end
def self.base_class; self; end
+ extend ActiveRecord::Configuration
include ActiveRecord::AttributeMethods
def self.define_attribute_methods
@@ -47,13 +47,13 @@ module ActiveRecord
instance = @klass.new
@klass.column_names.each do |name|
- assert !name.in?(instance.methods.map(&:to_s))
+ assert !instance.methods.map(&:to_s).include?(name)
end
@klass.define_attribute_methods
@klass.column_names.each do |name|
- assert name.in?(instance.methods.map(&:to_s)), "#{name} is not defined"
+ assert instance.methods.map(&:to_s).include?(name), "#{name} is not defined"
end
end
diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb
index 1093fedea1..4bc68acd13 100644
--- a/activerecord/test/cases/attribute_methods_test.rb
+++ b/activerecord/test/cases/attribute_methods_test.rb
@@ -1,5 +1,4 @@
require "cases/helper"
-require 'active_support/core_ext/object/inclusion'
require 'models/minimalistic'
require 'models/developer'
require 'models/auto_id'
@@ -35,7 +34,6 @@ class AttributeMethodsTest < ActiveRecord::TestCase
assert t.attribute_present?("written_on")
assert !t.attribute_present?("content")
assert !t.attribute_present?("author_name")
-
end
def test_attribute_present_with_booleans
@@ -484,9 +482,9 @@ class AttributeMethodsTest < ActiveRecord::TestCase
Topic.create(:title => 'Budget')
# Oracle does not support boolean expressions in SELECT
if current_adapter?(:OracleAdapter)
- topic = Topic.scoped(:select => "topics.*, 0 as is_test").first
+ topic = Topic.all.merge!(:select => "topics.*, 0 as is_test").first
else
- topic = Topic.scoped(:select => "topics.*, 1=2 as is_test").first
+ topic = Topic.all.merge!(:select => "topics.*, 1=2 as is_test").first
end
assert !topic.is_test?
end
@@ -495,9 +493,9 @@ class AttributeMethodsTest < ActiveRecord::TestCase
Topic.create(:title => 'Budget')
# Oracle does not support boolean expressions in SELECT
if current_adapter?(:OracleAdapter)
- topic = Topic.scoped(:select => "topics.*, 1 as is_test").first
+ topic = Topic.all.merge!(:select => "topics.*, 1 as is_test").first
else
- topic = Topic.scoped(:select => "topics.*, 2=2 as is_test").first
+ topic = Topic.all.merge!(:select => "topics.*, 2=2 as is_test").first
end
assert topic.is_test?
end
@@ -792,6 +790,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
end
private
+
def cached_columns
Topic.columns.find_all { |column|
!Topic.serialized_attributes.include? column.name
@@ -815,7 +814,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
end
def privatize(method_signature)
- @target.class_eval <<-private_method
+ @target.class_eval(<<-private_method, __FILE__, __LINE__ + 1)
private
def #{method_signature}
"I'm private"
diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb
index 8ef3bfef15..fd4f09ab36 100644
--- a/activerecord/test/cases/autosave_association_test.rb
+++ b/activerecord/test/cases/autosave_association_test.rb
@@ -20,22 +20,6 @@ require 'models/company'
require 'models/eye'
class TestAutosaveAssociationsInGeneral < ActiveRecord::TestCase
- def test_autosave_should_be_a_valid_option_for_has_one
- assert ActiveRecord::Associations::Builder::HasOne.valid_options.include?(:autosave)
- end
-
- def test_autosave_should_be_a_valid_option_for_belongs_to
- assert ActiveRecord::Associations::Builder::BelongsTo.valid_options.include?(:autosave)
- end
-
- def test_autosave_should_be_a_valid_option_for_has_many
- 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 ActiveRecord::Associations::Builder::HasAndBelongsToMany.valid_options.include?(:autosave)
- end
-
def test_should_not_add_the_same_callbacks_multiple_times_for_has_one
assert_no_difference_when_adding_callbacks_twice_for Pirate, :ship
end
@@ -155,7 +139,7 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
end
def test_not_resaved_when_unchanged
- firm = Firm.scoped(:includes => :account).first
+ firm = Firm.all.merge!(:includes => :account).first
firm.name += '-changed'
assert_queries(1) { firm.save! }
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
index f95230ff50..63981a68a9 100644
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -81,6 +81,12 @@ end
class BasicsTest < ActiveRecord::TestCase
fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts
+ def setup
+ ActiveRecord::Base.time_zone_aware_attributes = false
+ ActiveRecord::Base.default_timezone = :local
+ Time.zone = nil
+ end
+
def test_generated_methods_modules
modules = Computer.ancestors
assert modules.include?(Computer::GeneratedFeatureMethods)
@@ -125,36 +131,36 @@ class BasicsTest < ActiveRecord::TestCase
unless current_adapter?(:PostgreSQLAdapter,:OracleAdapter,:SQLServerAdapter)
def test_limit_with_comma
- assert Topic.limit("1,2").all
+ assert Topic.limit("1,2").to_a
end
end
def test_limit_without_comma
- assert_equal 1, Topic.limit("1").all.length
- assert_equal 1, Topic.limit(1).all.length
+ assert_equal 1, Topic.limit("1").to_a.length
+ assert_equal 1, Topic.limit(1).to_a.length
end
def test_invalid_limit
assert_raises(ArgumentError) do
- Topic.limit("asdfadf").all
+ Topic.limit("asdfadf").to_a
end
end
def test_limit_should_sanitize_sql_injection_for_limit_without_comas
assert_raises(ArgumentError) do
- Topic.limit("1 select * from schema").all
+ Topic.limit("1 select * from schema").to_a
end
end
def test_limit_should_sanitize_sql_injection_for_limit_with_comas
assert_raises(ArgumentError) do
- Topic.limit("1, 7 procedure help()").all
+ Topic.limit("1, 7 procedure help()").to_a
end
end
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
+ assert_equal 1, Topic.limit(Arel.sql('2-1')).to_a.length
end
end
@@ -225,6 +231,7 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal 11, Topic.find(1).written_on.sec
assert_equal 223300, Topic.find(1).written_on.usec
assert_equal 9900, Topic.find(2).written_on.usec
+ assert_equal 129346, Topic.find(3).written_on.usec
end
end
@@ -343,13 +350,13 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_load
- topics = Topic.scoped(:order => 'id').all
+ topics = Topic.all.merge!(:order => 'id').to_a
assert_equal(4, topics.size)
assert_equal(topics(:first).title, topics.first.title)
end
def test_load_with_condition
- topics = Topic.scoped(:where => "author_name = 'Mary'").all
+ topics = Topic.all.merge!(:where => "author_name = 'Mary'").to_a
assert_equal(1, topics.size)
assert_equal(topics(:second).title, topics.first.title)
@@ -504,7 +511,7 @@ class BasicsTest < ActiveRecord::TestCase
end
# Oracle, and Sybase do not have a TIME datatype.
- unless current_adapter?(:OracleAdapter, :SybaseAdapter, :SQLite3Adapter)
+ unless current_adapter?(:OracleAdapter, :SybaseAdapter)
def test_utc_as_time_zone
Topic.default_timezone = :utc
attributes = { "bonus_time" => "5:42:00AM" }
@@ -597,13 +604,19 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal "changed", post.body
end
+ def test_attr_readonly_is_class_level_setting
+ post = ReadonlyTitlePost.new
+ assert_raise(NoMethodError) { post._attr_readonly = [:title] }
+ assert_deprecated { post._attr_readonly }
+ end
+
def test_non_valid_identifier_column_name
weird = Weird.create('a$b' => 'value')
weird.reload
assert_equal 'value', weird.send('a$b')
assert_equal 'value', weird.read_attribute('a$b')
- weird.update_column('a$b', 'value2')
+ weird.update_columns('a$b' => 'value2')
weird.reload
assert_equal 'value2', weird.send('a$b')
assert_equal 'value2', weird.read_attribute('a$b')
@@ -686,7 +699,7 @@ class BasicsTest < ActiveRecord::TestCase
}
topic = Topic.find(1)
topic.attributes = attributes
- assert_equal Time.utc(2004, 6, 24, 16, 24, 0), topic.written_on
+ assert_equal Time.local(2004, 6, 24, 16, 24, 0), topic.written_on
end
def test_multiparameter_attributes_on_time_with_no_date
@@ -746,9 +759,6 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_multiparameter_attributes_on_time_will_ignore_hour_if_missing
- ActiveRecord::Base.time_zone_aware_attributes = false
- ActiveRecord::Base.default_timezone = :local
- Time.zone = nil
attributes = {
"written_on(1i)" => "2004", "written_on(2i)" => "12", "written_on(3i)" => "12",
"written_on(5i)" => "12", "written_on(6i)" => "02"
@@ -796,8 +806,6 @@ class BasicsTest < ActiveRecord::TestCase
topic = Topic.find(1)
topic.attributes = attributes
assert_equal Time.utc(2004, 6, 24, 16, 24, 0), topic.written_on
- ensure
- ActiveRecord::Base.default_timezone = :local
end
def test_multiparameter_attributes_on_time_with_time_zone_aware_attributes
@@ -813,14 +821,9 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal Time.utc(2004, 6, 24, 23, 24, 0), topic.written_on
assert_equal Time.utc(2004, 6, 24, 16, 24, 0), topic.written_on.time
assert_equal Time.zone, topic.written_on.time_zone
- ensure
- ActiveRecord::Base.time_zone_aware_attributes = false
- ActiveRecord::Base.default_timezone = :local
- Time.zone = nil
end
def test_multiparameter_attributes_on_time_with_time_zone_aware_attributes_false
- ActiveRecord::Base.time_zone_aware_attributes = false
Time.zone = ActiveSupport::TimeZone[-28800]
attributes = {
"written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
@@ -830,8 +833,6 @@ class BasicsTest < ActiveRecord::TestCase
topic.attributes = attributes
assert_equal Time.local(2004, 6, 24, 16, 24, 0), topic.written_on
assert_equal false, topic.written_on.respond_to?(:time_zone)
- ensure
- Time.zone = nil
end
def test_multiparameter_attributes_on_time_with_skip_time_zone_conversion_for_attributes
@@ -848,14 +849,11 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal Time.utc(2004, 6, 24, 16, 24, 0), topic.written_on
assert_equal false, topic.written_on.respond_to?(:time_zone)
ensure
- ActiveRecord::Base.time_zone_aware_attributes = false
- ActiveRecord::Base.default_timezone = :local
- Time.zone = nil
Topic.skip_time_zone_conversion_for_attributes = []
end
# Oracle, and Sybase do not have a TIME datatype.
- unless current_adapter?(:OracleAdapter, :SybaseAdapter, :SQLite3Adapter)
+ unless current_adapter?(:OracleAdapter, :SybaseAdapter)
def test_multiparameter_attributes_on_time_only_column_with_time_zone_aware_attributes_does_not_do_time_zone_conversion
ActiveRecord::Base.time_zone_aware_attributes = true
ActiveRecord::Base.default_timezone = :utc
@@ -868,17 +866,10 @@ class BasicsTest < ActiveRecord::TestCase
topic.attributes = attributes
assert_equal Time.utc(2000, 1, 1, 16, 24, 0), topic.bonus_time
assert topic.bonus_time.utc?
- ensure
- ActiveRecord::Base.time_zone_aware_attributes = false
- ActiveRecord::Base.default_timezone = :local
- Time.zone = nil
end
end
def test_multiparameter_attributes_on_time_with_empty_seconds
- ActiveRecord::Base.time_zone_aware_attributes = false
- ActiveRecord::Base.default_timezone = :local
- Time.zone = nil
attributes = {
"written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
"written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => ""
@@ -888,6 +879,41 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal Time.local(2004, 6, 24, 16, 24, 0), topic.written_on
end
+ def test_multiparameter_attributes_setting_time_attribute
+ return skip "Oracle does not have TIME data type" if current_adapter? :OracleAdapter
+
+ topic = Topic.new( "bonus_time(4i)"=> "01", "bonus_time(5i)" => "05" )
+ assert_equal 1, topic.bonus_time.hour
+ assert_equal 5, topic.bonus_time.min
+ end
+
+ def test_multiparameter_attributes_setting_date_attribute
+ topic = Topic.new( "written_on(1i)" => "1952", "written_on(2i)" => "3", "written_on(3i)" => "11" )
+ assert_equal 1952, topic.written_on.year
+ assert_equal 3, topic.written_on.month
+ assert_equal 11, topic.written_on.day
+ end
+
+ def test_multiparameter_attributes_setting_date_and_time_attribute
+ topic = Topic.new(
+ "written_on(1i)" => "1952",
+ "written_on(2i)" => "3",
+ "written_on(3i)" => "11",
+ "written_on(4i)" => "13",
+ "written_on(5i)" => "55")
+ assert_equal 1952, topic.written_on.year
+ assert_equal 3, topic.written_on.month
+ assert_equal 11, topic.written_on.day
+ assert_equal 13, topic.written_on.hour
+ assert_equal 55, topic.written_on.min
+ end
+
+ def test_multiparameter_attributes_setting_time_but_not_date_on_date_field
+ assert_raise( ActiveRecord::MultiparameterAssignmentErrors ) do
+ Topic.new( "written_on(4i)" => "13", "written_on(5i)" => "55" )
+ end
+ end
+
def test_multiparameter_assignment_of_aggregation
customer = Customer.new
address = Address.new("The Street", "The City", "The Country")
@@ -929,19 +955,20 @@ class BasicsTest < ActiveRecord::TestCase
attributes = { "address(1)" => "The Street", "address(2)" => address.city, "address(3000)" => address.country }
customer.attributes = attributes
end
+
assert_equal("address", ex.errors[0].attribute)
end
def test_attributes_on_dummy_time
# Oracle, and Sybase do not have a TIME datatype.
- return true if current_adapter?(:OracleAdapter, :SybaseAdapter, :SQLite3Adapter)
+ return true if current_adapter?(:OracleAdapter, :SybaseAdapter)
attributes = {
"bonus_time" => "5:42:00AM"
}
topic = Topic.find(1)
topic.attributes = attributes
- assert_equal Time.utc(2000, 1, 1, 5, 42, 0), topic.bonus_time
+ assert_equal Time.local(2000, 1, 1, 5, 42, 0), topic.bonus_time
end
def test_boolean
@@ -1263,10 +1290,10 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_quoting_arrays
- replies = Reply.scoped(:where => [ "id IN (?)", topics(:first).replies.collect(&:id) ]).all
+ replies = Reply.all.merge!(:where => [ "id IN (?)", topics(:first).replies.collect(&:id) ]).to_a
assert_equal topics(:first).replies.size, replies.size
- replies = Reply.scoped(:where => [ "id IN (?)", [] ]).all
+ replies = Reply.all.merge!(:where => [ "id IN (?)", [] ]).to_a
assert_equal 0, replies.size
end
@@ -1523,6 +1550,8 @@ class BasicsTest < ActiveRecord::TestCase
after_seq = Joke.sequence_name
assert_equal before_seq, after_seq unless before_seq.nil? && after_seq.nil?
+ ensure
+ Joke.reset_sequence_name
end
def test_dont_clear_inheritnce_column_when_setting_explicitly
@@ -1599,57 +1628,57 @@ class BasicsTest < ActiveRecord::TestCase
def test_no_limit_offset
assert_nothing_raised do
- Developer.scoped(:offset => 2).all
+ Developer.all.merge!(:offset => 2).to_a
end
end
def test_find_last
last = Developer.last
- assert_equal last, Developer.scoped(:order => 'id desc').first
+ assert_equal last, Developer.all.merge!(:order => 'id desc').first
end
def test_last
- assert_equal Developer.scoped(:order => 'id desc').first, Developer.last
+ assert_equal Developer.all.merge!(:order => 'id desc').first, Developer.last
end
def test_all
developers = Developer.all
- assert_kind_of Array, developers
+ assert_kind_of ActiveRecord::Relation, developers
assert_equal Developer.all, developers
end
def test_all_with_conditions
- assert_equal Developer.scoped(:order => 'id desc').all, Developer.order('id desc').all
+ assert_equal Developer.all.merge!(:order => 'id desc').to_a, Developer.order('id desc').to_a
end
def test_find_ordered_last
- last = Developer.scoped(:order => 'developers.salary ASC').last
- assert_equal last, Developer.scoped(:order => 'developers.salary ASC').all.last
+ last = Developer.all.merge!(:order => 'developers.salary ASC').last
+ assert_equal last, Developer.all.merge!(:order => 'developers.salary ASC').to_a.last
end
def test_find_reverse_ordered_last
- last = Developer.scoped(:order => 'developers.salary DESC').last
- assert_equal last, Developer.scoped(:order => 'developers.salary DESC').all.last
+ last = Developer.all.merge!(:order => 'developers.salary DESC').last
+ assert_equal last, Developer.all.merge!(:order => 'developers.salary DESC').to_a.last
end
def test_find_multiple_ordered_last
- last = Developer.scoped(:order => 'developers.name, developers.salary DESC').last
- assert_equal last, Developer.scoped(:order => 'developers.name, developers.salary DESC').all.last
+ last = Developer.all.merge!(:order => 'developers.name, developers.salary DESC').last
+ assert_equal last, Developer.all.merge!(:order => 'developers.name, developers.salary DESC').to_a.last
end
def test_find_keeps_multiple_order_values
- combined = Developer.scoped(:order => 'developers.name, developers.salary').all
- assert_equal combined, Developer.scoped(:order => ['developers.name', 'developers.salary']).all
+ combined = Developer.all.merge!(:order => 'developers.name, developers.salary').to_a
+ assert_equal combined, Developer.all.merge!(:order => ['developers.name', 'developers.salary']).to_a
end
def test_find_keeps_multiple_group_values
- combined = Developer.scoped(:group => 'developers.name, developers.salary, developers.id, developers.created_at, developers.updated_at').all
- assert_equal combined, Developer.scoped(:group => ['developers.name', 'developers.salary', 'developers.id', 'developers.created_at', 'developers.updated_at']).all
+ combined = Developer.all.merge!(:group => 'developers.name, developers.salary, developers.id, developers.created_at, developers.updated_at').to_a
+ assert_equal combined, Developer.all.merge!(:group => ['developers.name', 'developers.salary', 'developers.id', 'developers.created_at', 'developers.updated_at']).to_a
end
def test_find_symbol_ordered_last
- last = Developer.scoped(:order => :salary).last
- assert_equal last, Developer.scoped(:order => :salary).all.last
+ last = Developer.all.merge!(:order => :salary).last
+ assert_equal last, Developer.all.merge!(:order => :salary).to_a.last
end
def test_abstract_class
@@ -1662,18 +1691,6 @@ class BasicsTest < ActiveRecord::TestCase
assert_nil AbstractCompany.table_name
end
- def test_base_class
- assert_equal LoosePerson, LoosePerson.base_class
- assert_equal LooseDescendant, LooseDescendant.base_class
- assert_equal TightPerson, TightPerson.base_class
- assert_equal TightPerson, TightDescendant.base_class
-
- assert_equal Post, Post.base_class
- assert_equal Post, SpecialPost.base_class
- assert_equal Post, StiPost.base_class
- assert_equal SubStiPost, SubStiPost.base_class
- end
-
def test_descends_from_active_record
assert !ActiveRecord::Base.descends_from_active_record?
@@ -1727,6 +1744,12 @@ class BasicsTest < ActiveRecord::TestCase
assert_kind_of String, Client.first.to_param
end
+ def test_to_param_returns_id_even_if_not_persisted
+ client = Client.new
+ client.id = 1
+ assert_equal "1", client.to_param
+ end
+
def test_inspect_class
assert_equal 'ActiveRecord::Base', ActiveRecord::Base.inspect
assert_equal 'LoosePerson(abstract)', LoosePerson.inspect
@@ -1743,8 +1766,8 @@ class BasicsTest < ActiveRecord::TestCase
end
def test_inspect_limited_select_instance
- assert_equal %(#<Topic id: 1>), Topic.scoped(:select => 'id', :where => 'id = 1').first.inspect
- assert_equal %(#<Topic id: 1, title: "The First Topic">), Topic.scoped(:select => 'id, title', :where => 'id = 1').first.inspect
+ assert_equal %(#<Topic id: 1>), Topic.all.merge!(:select => 'id', :where => 'id = 1').first.inspect
+ assert_equal %(#<Topic id: 1, title: "The First Topic">), Topic.all.merge!(:select => 'id, title', :where => 'id = 1').first.inspect
end
def test_inspect_class_without_table
@@ -1857,7 +1880,7 @@ class BasicsTest < ActiveRecord::TestCase
def test_current_scope_is_reset
Object.const_set :UnloadablePost, Class.new(ActiveRecord::Base)
- UnloadablePost.send(:current_scope=, UnloadablePost.scoped)
+ UnloadablePost.send(:current_scope=, UnloadablePost.all)
UnloadablePost.unloadable
assert_not_nil Thread.current[:UnloadablePost_current_scope]
@@ -1924,8 +1947,6 @@ class BasicsTest < ActiveRecord::TestCase
est_key = Developer.first.cache_key
assert_equal utc_key, est_key
- ensure
- ActiveRecord::Base.time_zone_aware_attributes = false
end
def test_cache_key_format_for_existing_record_with_updated_at
@@ -1935,13 +1956,13 @@ class BasicsTest < ActiveRecord::TestCase
def test_cache_key_format_for_existing_record_with_nil_updated_at
dev = Developer.first
- dev.update_attribute(:updated_at, nil)
+ dev.update_columns(updated_at: nil)
assert_match(/\/#{dev.id}$/, dev.cache_key)
end
def test_uniq_delegates_to_scoped
scope = stub
- Bird.stubs(:scoped).returns(mock(:uniq => scope))
+ Bird.stubs(:all).returns(mock(:uniq => scope))
assert_equal scope, Bird.uniq
end
@@ -2008,7 +2029,7 @@ class BasicsTest < ActiveRecord::TestCase
scope.expects(meth).with(:foo, :bar).returns(record)
klass = Class.new(ActiveRecord::Base)
- klass.stubs(:scoped => scope)
+ klass.stubs(:all => scope)
assert_equal record, klass.public_send(meth, :foo, :bar)
end
@@ -2016,6 +2037,6 @@ class BasicsTest < ActiveRecord::TestCase
test "scoped can take a values hash" do
klass = Class.new(ActiveRecord::Base)
- assert_equal ['foo'], klass.scoped(select: 'foo').select_values
+ assert_equal ['foo'], klass.all.merge!(select: 'foo').select_values
end
end
diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb
index a279b0e77c..40e712072f 100644
--- a/activerecord/test/cases/calculations_test.rb
+++ b/activerecord/test/cases/calculations_test.rb
@@ -40,8 +40,8 @@ class CalculationsTest < ActiveRecord::TestCase
end
def test_type_cast_calculated_value_should_convert_db_averages_of_fixnum_class_to_decimal
- assert_equal 0, NumericData.scoped.send(:type_cast_calculated_value, 0, nil, 'avg')
- assert_equal 53.0, NumericData.scoped.send(:type_cast_calculated_value, 53, nil, 'avg')
+ assert_equal 0, NumericData.all.send(:type_cast_calculated_value, 0, nil, 'avg')
+ assert_equal 53.0, NumericData.all.send(:type_cast_calculated_value, 53, nil, 'avg')
end
def test_should_get_maximum_of_field
@@ -58,7 +58,16 @@ class CalculationsTest < ActiveRecord::TestCase
def test_should_group_by_field
c = Account.group(:firm_id).sum(:credit_limit)
- [1,6,2].each { |firm_id| assert c.keys.include?(firm_id) }
+ [1,6,2].each do |firm_id|
+ assert c.keys.include?(firm_id), "Group #{c.inspect} does not contain firm_id #{firm_id}"
+ end
+ end
+
+ def test_should_group_by_arel_attribute
+ c = Account.group(Account.arel_table[:firm_id]).sum(:credit_limit)
+ [1,6,2].each do |firm_id|
+ assert c.keys.include?(firm_id), "Group #{c.inspect} does not contain firm_id #{firm_id}"
+ end
end
def test_should_group_by_multiple_fields
@@ -82,24 +91,24 @@ class CalculationsTest < ActiveRecord::TestCase
end
def test_should_order_by_grouped_field
- c = Account.scoped(:group => :firm_id, :order => "firm_id").sum(:credit_limit)
+ c = Account.all.merge!(:group => :firm_id, :order => "firm_id").sum(:credit_limit)
assert_equal [1, 2, 6, 9], c.keys.compact
end
def test_should_order_by_calculation
- c = Account.scoped(:group => :firm_id, :order => "sum_credit_limit desc, firm_id").sum(:credit_limit)
+ c = Account.all.merge!(:group => :firm_id, :order => "sum_credit_limit desc, firm_id").sum(:credit_limit)
assert_equal [105, 60, 53, 50, 50], c.keys.collect { |k| c[k] }
assert_equal [6, 2, 9, 1], c.keys.compact
end
def test_should_limit_calculation
- c = Account.scoped(:where => "firm_id IS NOT NULL",
+ c = Account.all.merge!(:where => "firm_id IS NOT NULL",
:group => :firm_id, :order => "firm_id", :limit => 2).sum(:credit_limit)
assert_equal [1, 2], c.keys.compact
end
def test_should_limit_calculation_with_offset
- c = Account.scoped(:where => "firm_id IS NOT NULL", :group => :firm_id,
+ c = Account.all.merge!(:where => "firm_id IS NOT NULL", :group => :firm_id,
:order => "firm_id", :limit => 2, :offset => 1).sum(:credit_limit)
assert_equal [2, 6], c.keys.compact
end
@@ -150,7 +159,7 @@ class CalculationsTest < ActiveRecord::TestCase
end
def test_should_group_by_summed_field_having_condition
- c = Account.scoped(:group => :firm_id,
+ c = Account.all.merge!(:group => :firm_id,
:having => 'sum(credit_limit) > 50').sum(:credit_limit)
assert_nil c[1]
assert_equal 105, c[6]
@@ -186,7 +195,7 @@ class CalculationsTest < ActiveRecord::TestCase
end
def test_should_group_by_summed_field_with_conditions
- c = Account.scoped(:where => 'firm_id > 1',
+ c = Account.all.merge!(:where => 'firm_id > 1',
:group => :firm_id).sum(:credit_limit)
assert_nil c[1]
assert_equal 105, c[6]
@@ -194,7 +203,7 @@ class CalculationsTest < ActiveRecord::TestCase
end
def test_should_group_by_summed_field_with_conditions_and_having
- c = Account.scoped(:where => 'firm_id > 1',
+ c = Account.all.merge!(:where => 'firm_id > 1',
:group => :firm_id,
:having => 'sum(credit_limit) > 60').sum(:credit_limit)
assert_nil c[1]
@@ -317,19 +326,19 @@ class CalculationsTest < ActiveRecord::TestCase
def test_should_count_scoped_select
Account.update_all("credit_limit = NULL")
- assert_equal 0, Account.scoped(:select => "credit_limit").count
+ assert_equal 0, Account.all.merge!(:select => "credit_limit").count
end
def test_should_count_scoped_select_with_options
Account.update_all("credit_limit = NULL")
- Account.last.update_column('credit_limit', 49)
- Account.first.update_column('credit_limit', 51)
+ Account.last.update_columns('credit_limit' => 49)
+ Account.first.update_columns('credit_limit' => 51)
- assert_equal 1, Account.scoped(:select => "credit_limit").where('credit_limit >= 50').count
+ assert_equal 1, Account.all.merge!(:select => "credit_limit").where('credit_limit >= 50').count
end
def test_should_count_manual_select_with_include
- assert_equal 6, Account.scoped(:select => "DISTINCT accounts.id", :includes => :firm).count
+ assert_equal 6, Account.all.merge!(:select => "DISTINCT accounts.id", :includes => :firm).count
end
def test_count_with_column_parameter
@@ -346,7 +355,7 @@ class CalculationsTest < ActiveRecord::TestCase
end
def test_should_count_field_in_joined_table_with_group_by
- c = Account.scoped(:group => 'accounts.firm_id', :joins => :firm).count('companies.id')
+ c = Account.all.merge!(:group => 'accounts.firm_id', :joins => :firm).count('companies.id')
[1,6,2,9].each { |firm_id| assert c.keys.include?(firm_id) }
end
@@ -420,6 +429,40 @@ class CalculationsTest < ActiveRecord::TestCase
Account.where("credit_limit > 50").from('accounts').maximum(:credit_limit)
end
+ def test_maximum_with_not_auto_table_name_prefix_if_column_included
+ Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
+
+ # TODO: Investigate why PG isn't being typecast
+ if current_adapter?(:PostgreSQLAdapter) || current_adapter?(:MysqlAdapter)
+ assert_equal "7", Company.includes(:contracts).maximum(:developer_id)
+ else
+ assert_equal 7, Company.includes(:contracts).maximum(:developer_id)
+ end
+ end
+
+ def test_minimum_with_not_auto_table_name_prefix_if_column_included
+ Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
+
+ # TODO: Investigate why PG isn't being typecast
+ if current_adapter?(:PostgreSQLAdapter) || current_adapter?(:MysqlAdapter)
+ assert_equal "7", Company.includes(:contracts).minimum(:developer_id)
+ else
+ assert_equal 7, Company.includes(:contracts).minimum(:developer_id)
+ end
+ end
+
+ def test_sum_with_not_auto_table_name_prefix_if_column_included
+ Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
+
+ # TODO: Investigate why PG isn't being typecast
+ if current_adapter?(:MysqlAdapter) || current_adapter?(:PostgreSQLAdapter)
+ assert_equal "7", Company.includes(:contracts).sum(:developer_id)
+ else
+ assert_equal 7, Company.includes(:contracts).sum(:developer_id)
+ end
+ end
+
+
def test_from_option_with_specified_index
if Edge.connection.adapter_name == 'MySQL' or Edge.connection.adapter_name == 'Mysql2'
assert_equal Edge.count(:all), Edge.from('edges USE INDEX(unique_edge_index)').count(:all)
@@ -477,6 +520,11 @@ class CalculationsTest < ActiveRecord::TestCase
assert_equal [c.id], Company.joins(:contracts).pluck(:id)
end
+ def test_pluck_if_table_included
+ c = Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
+ assert_equal [c.id], Company.includes(:contracts).where("contracts.id" => c.contracts.first).pluck(:id)
+ end
+
def test_pluck_not_auto_table_name_prefix_if_column_joined
Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
assert_equal [7], Company.joins(:contracts).pluck(:developer_id)
@@ -493,11 +541,39 @@ class CalculationsTest < ActiveRecord::TestCase
assert_equal [50 + 53 + 55 + 60], Account.pluck('SUM(DISTINCT(credit_limit)) as credit_limit')
end
- def test_pluck_expects_a_single_selection
- assert_raise(ArgumentError) { Account.pluck 'id, credit_limit' }
- end
-
def test_plucks_with_ids
assert_equal Company.all.map(&:id).sort, Company.ids.sort
end
+
+ def test_pluck_not_auto_table_name_prefix_if_column_included
+ Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
+ ids = Company.includes(:contracts).pluck(:developer_id)
+ assert_equal Company.count, ids.length
+ assert_equal [7], ids.compact
+ end
+
+ def test_pluck_multiple_columns
+ assert_equal [
+ [1, "The First Topic"], [2, "The Second Topic of the day"],
+ [3, "The Third Topic of the day"], [4, "The Fourth Topic of the day"]
+ ], Topic.order(:id).pluck(:id, :title)
+ assert_equal [
+ [1, "The First Topic", "David"], [2, "The Second Topic of the day", "Mary"],
+ [3, "The Third Topic of the day", "Carl"], [4, "The Fourth Topic of the day", "Carl"]
+ ], Topic.order(:id).pluck(:id, :title, :author_name)
+ end
+
+ def test_pluck_with_multiple_columns_and_selection_clause
+ assert_equal [[1, 50], [2, 50], [3, 50], [4, 60], [5, 55], [6, 53]],
+ Account.pluck('id, credit_limit')
+ end
+
+ def test_pluck_with_multiple_columns_and_includes
+ Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
+ companies_and_developers = Company.order('companies.id').includes(:contracts).pluck(:name, :developer_id)
+
+ assert_equal Company.count, companies_and_developers.length
+ assert_equal ["37signals", nil], companies_and_developers.first
+ assert_equal ["test", 7], companies_and_developers.last
+ end
end
diff --git a/activerecord/test/cases/callbacks_test.rb b/activerecord/test/cases/callbacks_test.rb
index 7690769226..deeef3a3fd 100644
--- a/activerecord/test/cases/callbacks_test.rb
+++ b/activerecord/test/cases/callbacks_test.rb
@@ -426,11 +426,13 @@ class CallbacksTest < ActiveRecord::TestCase
def test_before_destroy_returning_false
david = ImmutableDeveloper.find(1)
assert !david.destroy
+ assert_raise(ActiveRecord::RecordNotDestroyed) { david.destroy! }
assert_not_nil ImmutableDeveloper.find_by_id(1)
someone = CallbackCancellationDeveloper.find(1)
someone.cancel_before_destroy = true
assert !someone.destroy
+ assert_raise(ActiveRecord::RecordNotDestroyed) { someone.destroy! }
assert !someone.after_destroy_called
end
diff --git a/activerecord/test/cases/column_definition_test.rb b/activerecord/test/cases/column_definition_test.rb
index a44b49466f..bd2fbaa7db 100644
--- a/activerecord/test/cases/column_definition_test.rb
+++ b/activerecord/test/cases/column_definition_test.rb
@@ -136,12 +136,6 @@ module ActiveRecord
smallint_column = PostgreSQLColumn.new('number', nil, oid, "smallint")
assert_equal :integer, smallint_column.type
end
-
- def test_uuid_column_should_map_to_string
- oid = PostgreSQLAdapter::OID::Identity.new
- uuid_column = PostgreSQLColumn.new('unique_id', nil, oid, "uuid")
- assert_equal :string, uuid_column.type
- end
end
end
end
diff --git a/activerecord/test/cases/column_test.rb b/activerecord/test/cases/column_test.rb
index 4111a5f808..a7b63d15c9 100644
--- a/activerecord/test/cases/column_test.rb
+++ b/activerecord/test/cases/column_test.rb
@@ -76,6 +76,12 @@ module ActiveRecord
date_string = Time.now.utc.strftime("%F")
assert_equal date_string, column.type_cast(date_string).strftime("%F")
end
+
+ def test_type_cast_duration_to_integer
+ column = Column.new("field", nil, "integer")
+ assert_equal 1800, column.type_cast(30.minutes)
+ assert_equal 7200, column.type_cast(2.hours)
+ end
end
end
end
diff --git a/activerecord/test/cases/connection_adapters/abstract_adapter_test.rb b/activerecord/test/cases/connection_adapters/abstract_adapter_test.rb
index 7dc6e8afcb..3e3d6e2769 100644
--- a/activerecord/test/cases/connection_adapters/abstract_adapter_test.rb
+++ b/activerecord/test/cases/connection_adapters/abstract_adapter_test.rb
@@ -36,7 +36,7 @@ module ActiveRecord
def test_close
pool = ConnectionPool.new(ConnectionSpecification.new({}, nil))
- pool.connections << adapter
+ pool.insert_connection_for_test! adapter
adapter.pool = pool
# Make sure the pool marks the connection in use
diff --git a/activerecord/test/cases/connection_adapters/connection_handler_test.rb b/activerecord/test/cases/connection_adapters/connection_handler_test.rb
index dc99ac665c..17cb447105 100644
--- a/activerecord/test/cases/connection_adapters/connection_handler_test.rb
+++ b/activerecord/test/cases/connection_adapters/connection_handler_test.rb
@@ -7,12 +7,11 @@ module ActiveRecord
@handler = ConnectionHandler.new
@handler.establish_connection 'america', Base.connection_pool.spec
@klass = Class.new do
+ include Model::Tag
def self.name; 'america'; end
- class << self
- alias active_record_super superclass
- end
end
@subklass = Class.new(@klass) do
+ include Model::Tag
def self.name; 'north america'; end
end
end
diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb
index bba7815d73..8287b35aaf 100644
--- a/activerecord/test/cases/connection_pool_test.rb
+++ b/activerecord/test/cases/connection_pool_test.rb
@@ -200,6 +200,110 @@ module ActiveRecord
end.join
end
+ # The connection pool is "fair" if threads waiting for
+ # connections receive them the order in which they began
+ # waiting. This ensures that we don't timeout one HTTP request
+ # even while well under capacity in a multi-threaded environment
+ # such as a Java servlet container.
+ #
+ # We don't need strict fairness: if two connections become
+ # available at the same time, it's fine of two threads that were
+ # waiting acquire the connections out of order.
+ #
+ # Thus this test prepares waiting threads and then trickles in
+ # available connections slowly, ensuring the wakeup order is
+ # correct in this case.
+ def test_checkout_fairness
+ @pool.instance_variable_set(:@size, 10)
+ expected = (1..@pool.size).to_a.freeze
+ # check out all connections so our threads start out waiting
+ conns = expected.map { @pool.checkout }
+ mutex = Mutex.new
+ order = []
+ errors = []
+
+ threads = expected.map do |i|
+ t = Thread.new {
+ begin
+ @pool.checkout # never checked back in
+ mutex.synchronize { order << i }
+ rescue => e
+ mutex.synchronize { errors << e }
+ end
+ }
+ Thread.pass until t.status == "sleep"
+ t
+ end
+
+ # this should wake up the waiting threads one by one in order
+ conns.each { |conn| @pool.checkin(conn); sleep 0.1 }
+
+ threads.each(&:join)
+
+ raise errors.first if errors.any?
+
+ assert_equal(expected, order)
+ end
+
+ # As mentioned in #test_checkout_fairness, we don't care about
+ # strict fairness. This test creates two groups of threads:
+ # group1 whose members all start waiting before any thread in
+ # group2. Enough connections are checked in to wakeup all
+ # group1 threads, and the fact that only group1 and no group2
+ # threads acquired a connection is enforced.
+ def test_checkout_fairness_by_group
+ @pool.instance_variable_set(:@size, 10)
+ # take all the connections
+ conns = (1..10).map { @pool.checkout }
+ mutex = Mutex.new
+ successes = [] # threads that successfully got a connection
+ errors = []
+
+ make_thread = proc do |i|
+ t = Thread.new {
+ begin
+ @pool.checkout # never checked back in
+ mutex.synchronize { successes << i }
+ rescue => e
+ mutex.synchronize { errors << e }
+ end
+ }
+ Thread.pass until t.status == "sleep"
+ t
+ end
+
+ # all group1 threads start waiting before any in group2
+ group1 = (1..5).map(&make_thread)
+ group2 = (6..10).map(&make_thread)
+
+ # checkin n connections back to the pool
+ checkin = proc do |n|
+ n.times do
+ c = conns.pop
+ @pool.checkin(c)
+ end
+ end
+
+ checkin.call(group1.size) # should wake up all group1
+
+ loop do
+ sleep 0.1
+ break if mutex.synchronize { (successes.size + errors.size) == group1.size }
+ end
+
+ winners = mutex.synchronize { successes.dup }
+ checkin.call(group2.size) # should wake up everyone remaining
+
+ group1.each(&:join)
+ group2.each(&:join)
+
+ assert_equal((1..group1.size).to_a, winners.sort)
+
+ if errors.any?
+ raise errors.first
+ end
+ end
+
def test_automatic_reconnect=
pool = ConnectionPool.new ActiveRecord::Base.connection_pool.spec
assert pool.automatic_reconnect
diff --git a/activerecord/test/cases/connection_specification/resolver_test.rb b/activerecord/test/cases/connection_specification/resolver_test.rb
index e6cb1b9521..673a2b2b88 100644
--- a/activerecord/test/cases/connection_specification/resolver_test.rb
+++ b/activerecord/test/cases/connection_specification/resolver_test.rb
@@ -9,6 +9,7 @@ module ActiveRecord
end
def test_url_host_no_db
+ skip "only if mysql is available" unless defined?(MysqlAdapter)
spec = resolve 'mysql://foo?encoding=utf8'
assert_equal({
:adapter => "mysql",
@@ -18,6 +19,7 @@ module ActiveRecord
end
def test_url_host_db
+ skip "only if mysql is available" unless defined?(MysqlAdapter)
spec = resolve 'mysql://foo/bar?encoding=utf8'
assert_equal({
:adapter => "mysql",
@@ -27,6 +29,7 @@ module ActiveRecord
end
def test_url_port
+ skip "only if mysql is available" unless defined?(MysqlAdapter)
spec = resolve 'mysql://foo:123?encoding=utf8'
assert_equal({
:adapter => "mysql",
diff --git a/activerecord/test/cases/counter_cache_test.rb b/activerecord/test/cases/counter_cache_test.rb
index cd3d19e783..ee443741ca 100644
--- a/activerecord/test/cases/counter_cache_test.rb
+++ b/activerecord/test/cases/counter_cache_test.rb
@@ -8,9 +8,11 @@ require 'models/category'
require 'models/categorization'
require 'models/dog'
require 'models/dog_lover'
+require 'models/person'
+require 'models/friendship'
class CounterCacheTest < ActiveRecord::TestCase
- fixtures :topics, :categories, :categorizations, :cars, :dogs, :dog_lovers
+ fixtures :topics, :categories, :categorizations, :cars, :dogs, :dog_lovers, :people, :friendships
class ::SpecialTopic < ::Topic
has_many :special_replies, :foreign_key => 'parent_id'
@@ -109,4 +111,11 @@ class CounterCacheTest < ActiveRecord::TestCase
Topic.update_counters([t1.id, t2.id], :replies_count => 2)
end
end
+
+ test "reset the right counter if two have the same foreign key" do
+ michael = people(:michael)
+ assert_nothing_raised(ActiveRecord::StatementInvalid) do
+ Person.reset_counters(michael.id, :followers)
+ end
+ end
end
diff --git a/activerecord/test/cases/custom_locking_test.rb b/activerecord/test/cases/custom_locking_test.rb
index 42ef51ef3e..e8290297e3 100644
--- a/activerecord/test/cases/custom_locking_test.rb
+++ b/activerecord/test/cases/custom_locking_test.rb
@@ -9,7 +9,7 @@ module ActiveRecord
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.scoped(:lock => 'LOCK IN SHARE MODE').find(1)
+ Person.all.merge!(:lock => 'LOCK IN SHARE MODE').find(1)
end
end
end
diff --git a/activerecord/test/cases/defaults_test.rb b/activerecord/test/cases/defaults_test.rb
index b3a281d960..deaf5252db 100644
--- a/activerecord/test/cases/defaults_test.rb
+++ b/activerecord/test/cases/defaults_test.rb
@@ -1,5 +1,4 @@
require "cases/helper"
-require 'active_support/core_ext/object/inclusion'
require 'models/default'
require 'models/entrant'
@@ -95,7 +94,7 @@ if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
assert_equal 0, klass.columns_hash['zero'].default
assert !klass.columns_hash['zero'].null
# 0 in MySQL 4, nil in 5.
- assert klass.columns_hash['omit'].default.in?([0, nil])
+ assert [0, nil].include?(klass.columns_hash['omit'].default)
assert !klass.columns_hash['omit'].null
assert_raise(ActiveRecord::StatementInvalid) { klass.create! }
diff --git a/activerecord/test/cases/deprecated_dynamic_methods_test.rb b/activerecord/test/cases/deprecated_dynamic_methods_test.rb
index 77a609f49a..392f5f4cd5 100644
--- a/activerecord/test/cases/deprecated_dynamic_methods_test.rb
+++ b/activerecord/test/cases/deprecated_dynamic_methods_test.rb
@@ -1,4 +1,4 @@
-# This file should be deleted when active_record_deprecated_finders is removed as
+# This file should be deleted when activerecord-deprecated_finders is removed as
# a dependency.
#
# It is kept for now as there is some fairly nuanced behaviour in the dynamic
@@ -336,21 +336,21 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase
def test_find_last_with_limit_gives_same_result_when_loaded_and_unloaded
scope = Topic.limit(2)
unloaded_last = scope.last
- loaded_last = scope.all.last
+ loaded_last = scope.to_a.last
assert_equal loaded_last, unloaded_last
end
def test_find_last_with_limit_and_offset_gives_same_result_when_loaded_and_unloaded
scope = Topic.offset(2).limit(2)
unloaded_last = scope.last
- loaded_last = scope.all.last
+ loaded_last = scope.to_a.last
assert_equal loaded_last, unloaded_last
end
def test_find_last_with_offset_gives_same_result_when_loaded_and_unloaded
scope = Topic.offset(3)
unloaded_last = scope.last
- loaded_last = scope.all.last
+ loaded_last = scope.to_a.last
assert_equal loaded_last, unloaded_last
end
@@ -368,17 +368,17 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase
end
def test_dynamic_find_all_should_respect_association_order
- assert_equal [companies(:second_client), companies(:first_client)], companies(:first_firm).clients_sorted_desc.scoped(:where => "type = 'Client'").all
+ assert_equal [companies(:second_client), companies(:first_client)], companies(:first_firm).clients_sorted_desc.where("type = 'Client'").to_a
assert_equal [companies(:second_client), companies(:first_client)], companies(:first_firm).clients_sorted_desc.find_all_by_type('Client')
end
def test_dynamic_find_all_should_respect_association_limit
- assert_equal 1, companies(:first_firm).limited_clients.scoped(:where => "type = 'Client'").all.length
+ assert_equal 1, companies(:first_firm).limited_clients.where("type = 'Client'").to_a.length
assert_equal 1, companies(:first_firm).limited_clients.find_all_by_type('Client').length
end
def test_dynamic_find_all_limit_should_override_association_limit
- assert_equal 2, companies(:first_firm).limited_clients.scoped(:where => "type = 'Client'", :limit => 9_000).all.length
+ assert_equal 2, companies(:first_firm).limited_clients.where("type = 'Client'").limit(9_000).to_a.length
assert_equal 2, companies(:first_firm).limited_clients.find_all_by_type('Client', :limit => 9_000).length
end
@@ -396,22 +396,22 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase
end
def test_dynamic_find_all_should_respect_association_order_for_through
- assert_equal [Comment.find(10), Comment.find(7), Comment.find(6), Comment.find(3)], authors(:david).comments_desc.scoped(:where => "comments.type = 'SpecialComment'").all
+ assert_equal [Comment.find(10), Comment.find(7), Comment.find(6), Comment.find(3)], authors(:david).comments_desc.where("comments.type = 'SpecialComment'").to_a
assert_equal [Comment.find(10), Comment.find(7), Comment.find(6), Comment.find(3)], authors(:david).comments_desc.find_all_by_type('SpecialComment')
end
def test_dynamic_find_all_should_respect_association_limit_for_through
- assert_equal 1, authors(:david).limited_comments.scoped(:where => "comments.type = 'SpecialComment'").all.length
+ assert_equal 1, authors(:david).limited_comments.where("comments.type = 'SpecialComment'").to_a.length
assert_equal 1, authors(:david).limited_comments.find_all_by_type('SpecialComment').length
end
def test_dynamic_find_all_order_should_override_association_limit_for_through
- assert_equal 4, authors(:david).limited_comments.scoped(:where => "comments.type = 'SpecialComment'", :limit => 9_000).all.length
+ assert_equal 4, authors(:david).limited_comments.where("comments.type = 'SpecialComment'").limit(9_000).to_a.length
assert_equal 4, authors(:david).limited_comments.find_all_by_type('SpecialComment', :limit => 9_000).length
end
def test_find_all_include_over_the_same_table_for_through
- assert_equal 2, people(:michael).posts.scoped(:includes => :people).all.length
+ assert_equal 2, people(:michael).posts.includes(:people).to_a.length
end
def test_find_or_create_by_resets_cached_counters
@@ -487,7 +487,7 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase
end
def test_dynamic_find_all_by_attributes
- authors = Author.scoped
+ authors = Author.all
davids = authors.find_all_by_name('David')
assert_kind_of Array, davids
@@ -495,7 +495,7 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase
end
def test_dynamic_find_or_initialize_by_attributes
- authors = Author.scoped
+ authors = Author.all
lifo = authors.find_or_initialize_by_name('Lifo')
assert_equal "Lifo", lifo.name
@@ -505,7 +505,7 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase
end
def test_dynamic_find_or_create_by_attributes
- authors = Author.scoped
+ authors = Author.all
lifo = authors.find_or_create_by_name('Lifo')
assert_equal "Lifo", lifo.name
@@ -515,7 +515,7 @@ class DeprecatedDynamicMethodsTest < ActiveRecord::TestCase
end
def test_dynamic_find_or_create_by_attributes_bang
- authors = Author.scoped
+ authors = Author.all
assert_raises(ActiveRecord::RecordInvalid) { authors.find_or_create_by_name!('') }
@@ -580,7 +580,7 @@ class DynamicScopeTest < ActiveRecord::TestCase
def test_dynamic_scope
assert_equal @test_klass.scoped_by_author_id(1).find(1), @test_klass.find(1)
- assert_equal @test_klass.scoped_by_author_id_and_title(1, "Welcome to the weblog").first, @test_klass.scoped(:where => { :author_id => 1, :title => "Welcome to the weblog"}).first
+ assert_equal @test_klass.scoped_by_author_id_and_title(1, "Welcome to the weblog").first, @test_klass.all.merge!(:where => { :author_id => 1, :title => "Welcome to the weblog"}).first
end
def test_dynamic_scope_should_create_methods_after_hitting_method_missing
@@ -600,7 +600,8 @@ class DynamicScopeMatchTest < ActiveRecord::TestCase
end
def test_scoped_by
- match = ActiveRecord::DynamicMatchers::Method.match(nil, "scoped_by_age_and_sex_and_location")
+ model = stub(attribute_aliases: {})
+ match = ActiveRecord::DynamicMatchers::Method.match(model, "scoped_by_age_and_sex_and_location")
assert_not_nil match
assert_equal %w(age sex location), match.attribute_names
end
diff --git a/activerecord/test/cases/dirty_test.rb b/activerecord/test/cases/dirty_test.rb
index 2650040a80..92677b9926 100644
--- a/activerecord/test/cases/dirty_test.rb
+++ b/activerecord/test/cases/dirty_test.rb
@@ -79,6 +79,17 @@ class DirtyTest < ActiveRecord::TestCase
end
end
+ def test_setting_time_attributes_with_time_zone_field_to_itself_should_not_be_marked_as_a_change
+ in_time_zone 'Paris' do
+ target = Class.new(ActiveRecord::Base)
+ target.table_name = 'pirates'
+
+ pirate = target.create
+ pirate.created_on = pirate.created_on
+ assert !pirate.created_on_changed?
+ end
+ end
+
def test_time_attributes_changes_without_time_zone_by_skip
in_time_zone 'Paris' do
target = Class.new(ActiveRecord::Base)
@@ -190,7 +201,7 @@ class DirtyTest < ActiveRecord::TestCase
end
end
- def test_nullable_integer_zero_to_string_zero_not_marked_as_changed
+ def test_integer_zero_to_string_zero_not_marked_as_changed
pirate = Pirate.new
pirate.parrot_id = 0
pirate.catchphrase = 'arrr'
@@ -202,6 +213,19 @@ class DirtyTest < ActiveRecord::TestCase
assert !pirate.changed?
end
+ def test_integer_zero_to_integer_zero_not_marked_as_changed
+ pirate = Pirate.new
+ pirate.parrot_id = 0
+ pirate.catchphrase = 'arrr'
+ assert pirate.save!
+
+ assert !pirate.changed?
+
+ pirate.parrot_id = 0
+ assert !pirate.changed?
+ end
+
+
def test_zero_to_blank_marked_as_changed
pirate = Pirate.new
pirate.catchphrase = "Yarrrr, me hearties"
@@ -413,7 +437,7 @@ class DirtyTest < ActiveRecord::TestCase
with_partial_updates(Topic) do
Topic.create!(:author_name => 'Bill', :content => {:a => "a"})
topic = Topic.select('id, author_name').first
- topic.update_column :author_name, 'John'
+ topic.update_columns author_name: 'John'
topic = Topic.first
assert_not_nil topic.content
end
@@ -485,16 +509,6 @@ class DirtyTest < ActiveRecord::TestCase
assert_not_nil pirate.previous_changes['updated_on'][1]
assert !pirate.previous_changes.key?('parrot_id')
assert !pirate.previous_changes.key?('created_on')
-
- pirate = Pirate.find_by_catchphrase("Ahoy!")
- pirate.update_attribute(:catchphrase, "Ninjas suck!")
-
- assert_equal 2, pirate.previous_changes.size
- assert_equal ["Ahoy!", "Ninjas suck!"], pirate.previous_changes['catchphrase']
- assert_not_nil pirate.previous_changes['updated_on'][0]
- assert_not_nil pirate.previous_changes['updated_on'][1]
- assert !pirate.previous_changes.key?('parrot_id')
- assert !pirate.previous_changes.key?('created_on')
end
if ActiveRecord::Base.connection.supports_migrations?
@@ -511,6 +525,21 @@ class DirtyTest < ActiveRecord::TestCase
end
end
+ def test_setting_time_attributes_with_time_zone_field_to_same_time_should_not_be_marked_as_a_change
+ in_time_zone 'Paris' do
+ target = Class.new(ActiveRecord::Base)
+ target.table_name = 'pirates'
+
+ created_on = Time.now
+
+ pirate = target.create(:created_on => created_on)
+ pirate.reload # Here mysql truncate the usec value to 0
+
+ pirate.created_on = created_on
+ assert !pirate.created_on_changed?
+ end
+ end
+
private
def with_partial_updates(klass, on = true)
old = klass.partial_updates?
diff --git a/activerecord/test/cases/explain_subscriber_test.rb b/activerecord/test/cases/explain_subscriber_test.rb
index e118add44c..91e1df91cd 100644
--- a/activerecord/test/cases/explain_subscriber_test.rb
+++ b/activerecord/test/cases/explain_subscriber_test.rb
@@ -6,14 +6,14 @@ if ActiveRecord::Base.connection.supports_explain?
def test_collects_nothing_if_available_queries_for_explain_is_nil
with_queries(nil) do
- SUBSCRIBER.call
+ SUBSCRIBER.finish(nil, nil, {})
assert_nil Thread.current[:available_queries_for_explain]
end
end
def test_collects_nothing_if_the_payload_has_an_exception
with_queries([]) do |queries|
- SUBSCRIBER.call(:exception => Exception.new)
+ SUBSCRIBER.finish(nil, nil, :exception => Exception.new)
assert queries.empty?
end
end
@@ -21,7 +21,7 @@ if ActiveRecord::Base.connection.supports_explain?
def test_collects_nothing_for_ignored_payloads
with_queries([]) do |queries|
ActiveRecord::ExplainSubscriber::IGNORED_PAYLOADS.each do |ip|
- SUBSCRIBER.call(:name => ip)
+ SUBSCRIBER.finish(nil, nil, :name => ip)
end
assert queries.empty?
end
@@ -31,7 +31,7 @@ if ActiveRecord::Base.connection.supports_explain?
sql = 'select 1 from users'
binds = [1, 2]
with_queries([]) do |queries|
- SUBSCRIBER.call(:name => 'SQL', :sql => sql, :binds => binds)
+ SUBSCRIBER.finish(nil, nil, :name => 'SQL', :sql => sql, :binds => binds)
assert_equal 1, queries.size
assert_equal sql, queries[0][0]
assert_equal binds, queries[0][1]
@@ -45,4 +45,4 @@ if ActiveRecord::Base.connection.supports_explain?
Thread.current[:available_queries_for_explain] = nil
end
end
-end \ No newline at end of file
+end
diff --git a/activerecord/test/cases/explain_test.rb b/activerecord/test/cases/explain_test.rb
index cb7781f8e7..6dce8ccdd1 100644
--- a/activerecord/test/cases/explain_test.rb
+++ b/activerecord/test/cases/explain_test.rb
@@ -20,7 +20,7 @@ if ActiveRecord::Base.connection.supports_explain?
end
with_threshold(0) do
- Car.where(:name => 'honda').all
+ Car.where(:name => 'honda').to_a
end
end
@@ -45,7 +45,7 @@ if ActiveRecord::Base.connection.supports_explain?
queries = Thread.current[:available_queries_for_explain] = []
with_threshold(0) do
- Car.where(:name => 'honda').all
+ Car.where(:name => 'honda').to_a
end
sql, binds = queries[0]
@@ -58,7 +58,7 @@ if ActiveRecord::Base.connection.supports_explain?
def test_collecting_queries_for_explain
result, queries = ActiveRecord::Base.collecting_queries_for_explain do
- Car.where(:name => 'honda').all
+ Car.where(:name => 'honda').to_a
end
sql, binds = queries[0]
@@ -68,6 +68,16 @@ if ActiveRecord::Base.connection.supports_explain?
assert_equal [cars(:honda)], result
end
+ def test_logging_query_plan_when_counting_by_sql
+ base.logger.expects(:warn).with do |message|
+ message.starts_with?('EXPLAIN for:')
+ end
+
+ with_threshold(0) do
+ Car.count_by_sql "SELECT COUNT(*) FROM cars WHERE name = 'honda'"
+ end
+ end
+
def test_exec_explain_with_no_binds
sqls = %w(foo bar)
binds = [[], []]
diff --git a/activerecord/test/cases/finder_respond_to_test.rb b/activerecord/test/cases/finder_respond_to_test.rb
index 810c1500cc..9440cd429a 100644
--- a/activerecord/test/cases/finder_respond_to_test.rb
+++ b/activerecord/test/cases/finder_respond_to_test.rb
@@ -36,6 +36,11 @@ class FinderRespondToTest < ActiveRecord::TestCase
assert_respond_to Topic, :find_by_title_and_author_name
end
+ def test_should_respond_to_find_all_by_an_aliased_attribute
+ ensure_topic_method_is_not_cached(:find_by_heading)
+ assert_respond_to Topic, :find_by_heading
+ end
+
def test_should_respond_to_find_or_initialize_from_one_attribute
ensure_topic_method_is_not_cached(:find_or_initialize_by_title)
assert_respond_to Topic, :find_or_initialize_by_title
@@ -80,7 +85,6 @@ class FinderRespondToTest < ActiveRecord::TestCase
private
def ensure_topic_method_is_not_cached(method_id)
- class << Topic; self; end.send(:remove_method, method_id) if Topic.public_methods.any? { |m| m.to_s == method_id.to_s }
+ class << Topic; self; end.send(:remove_method, method_id) if Topic.public_methods.include? method_id
end
-
end
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
index f7ecab28ce..20c8e8894d 100644
--- a/activerecord/test/cases/finder_test.rb
+++ b/activerecord/test/cases/finder_test.rb
@@ -45,10 +45,20 @@ class FinderTest < ActiveRecord::TestCase
assert_raise(NoMethodError) { Topic.exists?([1,2]) }
end
+ def test_exists_does_not_select_columns_without_alias
+ assert_sql(/SELECT\W+1 AS one FROM ["`]topics["`]/i) do
+ Topic.exists?
+ end
+ end
+
def test_exists_returns_true_with_one_record_and_no_args
assert Topic.exists?
end
+ def test_exists_returns_false_with_false_arg
+ assert !Topic.exists?(false)
+ end
+
# exists? should handle nil for id's that come from URLs and always return false
# (example: Topic.exists?(params[:id])) where params[:id] is nil
def test_exists_with_nil_arg
@@ -63,7 +73,12 @@ class FinderTest < ActiveRecord::TestCase
assert Topic.order(:id).uniq.exists?
end
- def test_does_not_exist_with_empty_table_and_no_args_given
+ def test_exists_with_includes_limit_and_empty_result
+ assert !Topic.includes(:replies).limit(0).exists?
+ assert !Topic.includes(:replies).limit(1).where('0 = 1').exists?
+ end
+
+ def test_exists_with_empty_table_and_no_args_given
Topic.delete_all
assert !Topic.exists?
end
@@ -99,14 +114,14 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_by_ids_with_limit_and_offset
- assert_equal 2, Entrant.scoped(:limit => 2).find([1,3,2]).size
- assert_equal 1, Entrant.scoped(:limit => 3, :offset => 2).find([1,3,2]).size
+ assert_equal 2, Entrant.all.merge!(:limit => 2).find([1,3,2]).size
+ assert_equal 1, Entrant.all.merge!(:limit => 3, :offset => 2).find([1,3,2]).size
# Also test an edge case: If you have 11 results, and you set a
# limit of 3 and offset of 9, then you should find that there
# will be only 2 results, regardless of the limit.
devs = Developer.all
- last_devs = Developer.scoped(:limit => 3, :offset => 9).find devs.map(&:id)
+ last_devs = Developer.all.merge!(:limit => 3, :offset => 9).find devs.map(&:id)
assert_equal 2, last_devs.size
end
@@ -123,7 +138,7 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_with_group_and_sanitized_having_method
- developers = Developer.group(:salary).having("sum(salary) > ?", 10000).select('salary').all
+ developers = Developer.group(:salary).having("sum(salary) > ?", 10000).select('salary').to_a
assert_equal 3, developers.size
assert_equal 3, developers.map(&:salary).uniq.size
assert developers.all? { |developer| developer.salary > 10000 }
@@ -259,7 +274,7 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_only_some_columns
- topic = Topic.scoped(:select => "author_name").find(1)
+ topic = Topic.all.merge!(:select => "author_name").find(1)
assert_raise(ActiveModel::MissingAttributeError) {topic.title}
assert_nil topic.read_attribute("title")
assert_equal "David", topic.author_name
@@ -270,23 +285,23 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_on_array_conditions
- assert Topic.scoped(:where => ["approved = ?", false]).find(1)
- assert_raise(ActiveRecord::RecordNotFound) { Topic.scoped(:where => ["approved = ?", true]).find(1) }
+ assert Topic.all.merge!(:where => ["approved = ?", false]).find(1)
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => ["approved = ?", true]).find(1) }
end
def test_find_on_hash_conditions
- assert Topic.scoped(:where => { :approved => false }).find(1)
- assert_raise(ActiveRecord::RecordNotFound) { Topic.scoped(:where => { :approved => true }).find(1) }
+ assert Topic.all.merge!(:where => { :approved => false }).find(1)
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { :approved => true }).find(1) }
end
def test_find_on_hash_conditions_with_explicit_table_name
- assert Topic.scoped(:where => { 'topics.approved' => false }).find(1)
- assert_raise(ActiveRecord::RecordNotFound) { Topic.scoped(:where => { 'topics.approved' => true }).find(1) }
+ assert Topic.all.merge!(:where => { 'topics.approved' => false }).find(1)
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { 'topics.approved' => true }).find(1) }
end
def test_find_on_hash_conditions_with_hashed_table_name
- assert Topic.scoped(:where => {:topics => { :approved => false }}).find(1)
- assert_raise(ActiveRecord::RecordNotFound) { Topic.scoped(:where => {:topics => { :approved => true }}).find(1) }
+ assert Topic.all.merge!(:where => {:topics => { :approved => false }}).find(1)
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => {:topics => { :approved => true }}).find(1) }
end
def test_find_with_hash_conditions_on_joined_table
@@ -296,16 +311,16 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_with_hash_conditions_on_joined_table_and_with_range
- firms = DependentFirm.scoped :joins => :account, :where => {:name => 'RailsCore', :accounts => { :credit_limit => 55..60 }}
+ firms = DependentFirm.all.merge!(:joins => :account, :where => {:name => 'RailsCore', :accounts => { :credit_limit => 55..60 }})
assert_equal 1, firms.size
assert_equal companies(:rails_core), firms.first
end
def test_find_on_hash_conditions_with_explicit_table_name_and_aggregate
david = customers(:david)
- assert Customer.scoped(:where => { 'customers.name' => david.name, :address => david.address }).find(david.id)
+ assert Customer.where('customers.name' => david.name, :address => david.address).find(david.id)
assert_raise(ActiveRecord::RecordNotFound) {
- Customer.scoped(:where => { 'customers.name' => david.name + "1", :address => david.address }).find(david.id)
+ Customer.where('customers.name' => david.name + "1", :address => david.address).find(david.id)
}
end
@@ -314,71 +329,71 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_on_hash_conditions_with_range
- assert_equal [1,2], Topic.scoped(:where => { :id => 1..2 }).all.map(&:id).sort
- assert_raise(ActiveRecord::RecordNotFound) { Topic.scoped(:where => { :id => 2..3 }).find(1) }
+ assert_equal [1,2], Topic.all.merge!(:where => { :id => 1..2 }).to_a.map(&:id).sort
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { :id => 2..3 }).find(1) }
end
def test_find_on_hash_conditions_with_end_exclusive_range
- assert_equal [1,2,3], Topic.scoped(:where => { :id => 1..3 }).all.map(&:id).sort
- assert_equal [1,2], Topic.scoped(:where => { :id => 1...3 }).all.map(&:id).sort
- assert_raise(ActiveRecord::RecordNotFound) { Topic.scoped(:where => { :id => 2...3 }).find(3) }
+ assert_equal [1,2,3], Topic.all.merge!(:where => { :id => 1..3 }).to_a.map(&:id).sort
+ assert_equal [1,2], Topic.all.merge!(:where => { :id => 1...3 }).to_a.map(&:id).sort
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { :id => 2...3 }).find(3) }
end
def test_find_on_hash_conditions_with_multiple_ranges
- assert_equal [1,2,3], Comment.scoped(:where => { :id => 1..3, :post_id => 1..2 }).all.map(&:id).sort
- assert_equal [1], Comment.scoped(:where => { :id => 1..1, :post_id => 1..10 }).all.map(&:id).sort
+ assert_equal [1,2,3], Comment.all.merge!(:where => { :id => 1..3, :post_id => 1..2 }).to_a.map(&:id).sort
+ assert_equal [1], Comment.all.merge!(:where => { :id => 1..1, :post_id => 1..10 }).to_a.map(&:id).sort
end
def test_find_on_hash_conditions_with_array_of_integers_and_ranges
- assert_equal [1,2,3,5,6,7,8,9], Comment.scoped(:where => {:id => [1..2, 3, 5, 6..8, 9]}).all.map(&:id).sort
+ assert_equal [1,2,3,5,6,7,8,9], Comment.all.merge!(:where => {:id => [1..2, 3, 5, 6..8, 9]}).to_a.map(&:id).sort
end
def test_find_on_multiple_hash_conditions
- assert Topic.scoped(:where => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => false }).find(1)
- assert_raise(ActiveRecord::RecordNotFound) { Topic.scoped(:where => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }).find(1) }
- assert_raise(ActiveRecord::RecordNotFound) { Topic.scoped(:where => { :author_name => "David", :title => "HHC", :replies_count => 1, :approved => false }).find(1) }
- assert_raise(ActiveRecord::RecordNotFound) { Topic.scoped(:where => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }).find(1) }
+ assert Topic.all.merge!(:where => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => false }).find(1)
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }).find(1) }
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { :author_name => "David", :title => "HHC", :replies_count => 1, :approved => false }).find(1) }
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.all.merge!(:where => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }).find(1) }
end
def test_condition_interpolation
assert_kind_of Firm, Company.where("name = '%s'", "37signals").first
- assert_nil Company.scoped(:where => ["name = '%s'", "37signals!"]).first
- assert_nil Company.scoped(:where => ["name = '%s'", "37signals!' OR 1=1"]).first
- assert_kind_of Time, Topic.scoped(:where => ["id = %d", 1]).first.written_on
+ assert_nil Company.all.merge!(:where => ["name = '%s'", "37signals!"]).first
+ assert_nil Company.all.merge!(:where => ["name = '%s'", "37signals!' OR 1=1"]).first
+ assert_kind_of Time, Topic.all.merge!(:where => ["id = %d", 1]).first.written_on
end
def test_condition_array_interpolation
- assert_kind_of Firm, Company.scoped(:where => ["name = '%s'", "37signals"]).first
- assert_nil Company.scoped(:where => ["name = '%s'", "37signals!"]).first
- assert_nil Company.scoped(:where => ["name = '%s'", "37signals!' OR 1=1"]).first
- assert_kind_of Time, Topic.scoped(:where => ["id = %d", 1]).first.written_on
+ assert_kind_of Firm, Company.all.merge!(:where => ["name = '%s'", "37signals"]).first
+ assert_nil Company.all.merge!(:where => ["name = '%s'", "37signals!"]).first
+ assert_nil Company.all.merge!(:where => ["name = '%s'", "37signals!' OR 1=1"]).first
+ assert_kind_of Time, Topic.all.merge!(:where => ["id = %d", 1]).first.written_on
end
def test_condition_hash_interpolation
- assert_kind_of Firm, Company.scoped(:where => { :name => "37signals"}).first
- assert_nil Company.scoped(:where => { :name => "37signals!"}).first
- assert_kind_of Time, Topic.scoped(:where => {:id => 1}).first.written_on
+ assert_kind_of Firm, Company.all.merge!(:where => { :name => "37signals"}).first
+ assert_nil Company.all.merge!(:where => { :name => "37signals!"}).first
+ assert_kind_of Time, Topic.all.merge!(:where => {:id => 1}).first.written_on
end
def test_hash_condition_find_malformed
assert_raise(ActiveRecord::StatementInvalid) {
- Company.scoped(:where => { :id => 2, :dhh => true }).first
+ Company.all.merge!(:where => { :id => 2, :dhh => true }).first
}
end
def test_hash_condition_find_with_escaped_characters
Company.create("name" => "Ain't noth'n like' \#stuff")
- assert Company.scoped(:where => { :name => "Ain't noth'n like' \#stuff" }).first
+ assert Company.all.merge!(:where => { :name => "Ain't noth'n like' \#stuff" }).first
end
def test_hash_condition_find_with_array
- p1, p2 = Post.scoped(:limit => 2, :order => 'id asc').all
- assert_equal [p1, p2], Post.scoped(:where => { :id => [p1, p2] }, :order => 'id asc').all
- assert_equal [p1, p2], Post.scoped(:where => { :id => [p1, p2.id] }, :order => 'id asc').all
+ p1, p2 = Post.all.merge!(:limit => 2, :order => 'id asc').to_a
+ assert_equal [p1, p2], Post.all.merge!(:where => { :id => [p1, p2] }, :order => 'id asc').to_a
+ assert_equal [p1, p2], Post.all.merge!(:where => { :id => [p1, p2.id] }, :order => 'id asc').to_a
end
def test_hash_condition_find_with_nil
- topic = Topic.scoped(:where => { :last_read => nil } ).first
+ topic = Topic.all.merge!(:where => { :last_read => nil } ).first
assert_not_nil topic
assert_nil topic.last_read
end
@@ -386,42 +401,42 @@ class FinderTest < ActiveRecord::TestCase
def test_hash_condition_find_with_aggregate_having_one_mapping
balance = customers(:david).balance
assert_kind_of Money, balance
- found_customer = Customer.scoped(:where => {:balance => balance}).first
+ found_customer = Customer.where(:balance => balance).first
assert_equal customers(:david), found_customer
end
def test_hash_condition_find_with_aggregate_attribute_having_same_name_as_field_and_key_value_being_aggregate
gps_location = customers(:david).gps_location
assert_kind_of GpsLocation, gps_location
- found_customer = Customer.scoped(:where => {:gps_location => gps_location}).first
+ found_customer = Customer.where(:gps_location => gps_location).first
assert_equal customers(:david), found_customer
end
def test_hash_condition_find_with_aggregate_having_one_mapping_and_key_value_being_attribute_value
balance = customers(:david).balance
assert_kind_of Money, balance
- found_customer = Customer.scoped(:where => {:balance => balance.amount}).first
+ found_customer = Customer.where(:balance => balance.amount).first
assert_equal customers(:david), found_customer
end
def test_hash_condition_find_with_aggregate_attribute_having_same_name_as_field_and_key_value_being_attribute_value
gps_location = customers(:david).gps_location
assert_kind_of GpsLocation, gps_location
- found_customer = Customer.scoped(:where => {:gps_location => gps_location.gps_location}).first
+ found_customer = Customer.where(:gps_location => gps_location.gps_location).first
assert_equal customers(:david), found_customer
end
def test_hash_condition_find_with_aggregate_having_three_mappings
address = customers(:david).address
assert_kind_of Address, address
- found_customer = Customer.scoped(:where => {:address => address}).first
+ found_customer = Customer.where(:address => address).first
assert_equal customers(:david), found_customer
end
def test_hash_condition_find_with_one_condition_being_aggregate_and_another_not
address = customers(:david).address
assert_kind_of Address, address
- found_customer = Customer.scoped(:where => {:address => address, :name => customers(:david).name}).first
+ found_customer = Customer.where(:address => address, :name => customers(:david).name).first
assert_equal customers(:david), found_customer
end
@@ -429,7 +444,7 @@ class FinderTest < ActiveRecord::TestCase
with_env_tz 'America/New_York' do
with_active_record_default_timezone :local do
topic = Topic.first
- assert_equal topic, Topic.scoped(:where => ['written_on = ?', topic.written_on.getutc]).first
+ assert_equal topic, Topic.all.merge!(:where => ['written_on = ?', topic.written_on.getutc]).first
end
end
end
@@ -438,7 +453,7 @@ class FinderTest < ActiveRecord::TestCase
with_env_tz 'America/New_York' do
with_active_record_default_timezone :local do
topic = Topic.first
- assert_equal topic, Topic.scoped(:where => {:written_on => topic.written_on.getutc}).first
+ assert_equal topic, Topic.all.merge!(:where => {:written_on => topic.written_on.getutc}).first
end
end
end
@@ -447,7 +462,7 @@ class FinderTest < ActiveRecord::TestCase
with_env_tz 'America/New_York' do
with_active_record_default_timezone :utc do
topic = Topic.first
- assert_equal topic, Topic.scoped(:where => ['written_on = ?', topic.written_on.getlocal]).first
+ assert_equal topic, Topic.all.merge!(:where => ['written_on = ?', topic.written_on.getlocal]).first
end
end
end
@@ -456,32 +471,32 @@ class FinderTest < ActiveRecord::TestCase
with_env_tz 'America/New_York' do
with_active_record_default_timezone :utc do
topic = Topic.first
- assert_equal topic, Topic.scoped(:where => {:written_on => topic.written_on.getlocal}).first
+ assert_equal topic, Topic.all.merge!(:where => {:written_on => topic.written_on.getlocal}).first
end
end
end
def test_bind_variables
- assert_kind_of Firm, Company.scoped(:where => ["name = ?", "37signals"]).first
- assert_nil Company.scoped(:where => ["name = ?", "37signals!"]).first
- assert_nil Company.scoped(:where => ["name = ?", "37signals!' OR 1=1"]).first
- assert_kind_of Time, Topic.scoped(:where => ["id = ?", 1]).first.written_on
+ assert_kind_of Firm, Company.all.merge!(:where => ["name = ?", "37signals"]).first
+ assert_nil Company.all.merge!(:where => ["name = ?", "37signals!"]).first
+ assert_nil Company.all.merge!(:where => ["name = ?", "37signals!' OR 1=1"]).first
+ assert_kind_of Time, Topic.all.merge!(:where => ["id = ?", 1]).first.written_on
assert_raise(ActiveRecord::PreparedStatementInvalid) {
- Company.scoped(:where => ["id=? AND name = ?", 2]).first
+ Company.all.merge!(:where => ["id=? AND name = ?", 2]).first
}
assert_raise(ActiveRecord::PreparedStatementInvalid) {
- Company.scoped(:where => ["id=?", 2, 3, 4]).first
+ Company.all.merge!(:where => ["id=?", 2, 3, 4]).first
}
end
def test_bind_variables_with_quotes
Company.create("name" => "37signals' go'es agains")
- assert Company.scoped(:where => ["name = ?", "37signals' go'es agains"]).first
+ assert Company.all.merge!(:where => ["name = ?", "37signals' go'es agains"]).first
end
def test_named_bind_variables_with_quotes
Company.create("name" => "37signals' go'es agains")
- assert Company.scoped(:where => ["name = :name", {:name => "37signals' go'es agains"}]).first
+ assert Company.all.merge!(:where => ["name = :name", {:name => "37signals' go'es agains"}]).first
end
def test_bind_arity
@@ -499,10 +514,10 @@ class FinderTest < ActiveRecord::TestCase
assert_nothing_raised { bind("'+00:00'", :foo => "bar") }
- assert_kind_of Firm, Company.scoped(:where => ["name = :name", { :name => "37signals" }]).first
- assert_nil Company.scoped(:where => ["name = :name", { :name => "37signals!" }]).first
- assert_nil Company.scoped(:where => ["name = :name", { :name => "37signals!' OR 1=1" }]).first
- assert_kind_of Time, Topic.scoped(:where => ["id = :id", { :id => 1 }]).first.written_on
+ assert_kind_of Firm, Company.all.merge!(:where => ["name = :name", { :name => "37signals" }]).first
+ assert_nil Company.all.merge!(:where => ["name = :name", { :name => "37signals!" }]).first
+ assert_nil Company.all.merge!(:where => ["name = :name", { :name => "37signals!' OR 1=1" }]).first
+ assert_kind_of Time, Topic.all.merge!(:where => ["id = :id", { :id => 1 }]).first.written_on
end
class SimpleEnumerable
@@ -589,6 +604,11 @@ class FinderTest < ActiveRecord::TestCase
assert_raise(ActiveRecord::RecordNotFound) { Topic.find_by_title!("The First Topic!") }
end
+ def test_find_by_one_attribute_that_is_an_alias
+ assert_equal topics(:first), Topic.find_by_heading("The First Topic")
+ assert_nil Topic.find_by_heading("The First Topic!")
+ end
+
def test_find_by_one_attribute_with_conditions
assert_equal accounts(:rails_core_account), Account.where('firm_id = ?', 6).find_by_credit_limit(50)
end
@@ -629,7 +649,7 @@ class FinderTest < ActiveRecord::TestCase
def test_dynamic_finder_on_one_attribute_with_conditions_returns_same_results_after_caching
# ensure this test can run independently of order
- class << Account; self; end.send(:remove_method, :find_by_credit_limit) if Account.public_methods.any? { |m| m.to_s == 'find_by_credit_limit' }
+ class << Account; self; end.send(:remove_method, :find_by_credit_limit) if Account.public_methods.include?(:find_by_credit_limit)
a = Account.where('firm_id = ?', 6).find_by_credit_limit(50)
assert_equal a, Account.where('firm_id = ?', 6).find_by_credit_limit(50) # find_by_credit_limit has been cached
end
@@ -674,10 +694,10 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_all_with_join
- developers_on_project_one = Developer.scoped(
+ developers_on_project_one = Developer.all.merge!(
:joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id',
:where => 'project_id=1'
- ).all
+ ).to_a
assert_equal 3, developers_on_project_one.length
developer_names = developers_on_project_one.map { |d| d.name }
assert developer_names.include?('David')
@@ -685,7 +705,7 @@ class FinderTest < ActiveRecord::TestCase
end
def test_joins_dont_clobber_id
- first = Firm.scoped(
+ first = Firm.all.merge!(
:joins => 'INNER JOIN companies clients ON clients.firm_id = companies.id',
:where => 'companies.id = 1'
).first
@@ -693,7 +713,7 @@ class FinderTest < ActiveRecord::TestCase
end
def test_joins_with_string_array
- person_with_reader_and_post = Post.scoped(
+ person_with_reader_and_post = Post.all.merge!(
:joins => [
"INNER JOIN categorizations ON categorizations.post_id = posts.id",
"INNER JOIN categories ON categories.id = categorizations.category_id AND categories.type = 'SpecialCategory'"
@@ -723,9 +743,9 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_by_records
- p1, p2 = Post.scoped(:limit => 2, :order => 'id asc').all
- assert_equal [p1, p2], Post.scoped(:where => ['id in (?)', [p1, p2]], :order => 'id asc')
- assert_equal [p1, p2], Post.scoped(:where => ['id in (?)', [p1, p2.id]], :order => 'id asc')
+ p1, p2 = Post.all.merge!(:limit => 2, :order => 'id asc').to_a
+ assert_equal [p1, p2], Post.all.merge!(:where => ['id in (?)', [p1, p2]], :order => 'id asc')
+ assert_equal [p1, p2], Post.all.merge!(:where => ['id in (?)', [p1, p2.id]], :order => 'id asc')
end
def test_select_value
@@ -752,14 +772,14 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_with_order_on_included_associations_with_construct_finder_sql_for_association_limiting_and_is_distinct
- assert_equal 2, Post.scoped(:includes => { :authors => :author_address }, :order => 'author_addresses.id DESC ', :limit => 2).all.size
+ assert_equal 2, Post.all.merge!(:includes => { :authors => :author_address }, :order => 'author_addresses.id DESC ', :limit => 2).to_a.size
- assert_equal 3, Post.scoped(:includes => { :author => :author_address, :authors => :author_address},
- :order => 'author_addresses_authors.id DESC ', :limit => 3).all.size
+ assert_equal 3, Post.all.merge!(:includes => { :author => :author_address, :authors => :author_address},
+ :order => 'author_addresses_authors.id DESC ', :limit => 3).to_a.size
end
def test_find_with_nil_inside_set_passed_for_one_attribute
- client_of = Company.scoped(
+ client_of = Company.all.merge!(
:where => {
:client_of => [2, 1, nil],
:name => ['37signals', 'Summit', 'Microsoft'] },
@@ -771,7 +791,7 @@ class FinderTest < ActiveRecord::TestCase
end
def test_find_with_nil_inside_set_passed_for_attribute
- client_of = Company.scoped(
+ client_of = Company.all.merge!(
:where => { :client_of => [nil] },
:order => 'client_of DESC'
).map { |x| x.client_of }
@@ -780,10 +800,10 @@ class FinderTest < ActiveRecord::TestCase
end
def test_with_limiting_with_custom_select
- posts = Post.references(:authors).scoped(
+ posts = Post.references(:authors).merge(
:includes => :author, :select => ' posts.*, authors.id as "author_id"',
:limit => 3, :order => 'posts.id'
- ).all
+ ).to_a
assert_equal 3, posts.size
assert_equal [0, 1, 1], posts.map(&:author_id).sort
end
@@ -798,7 +818,7 @@ class FinderTest < ActiveRecord::TestCase
end
def test_finder_with_offset_string
- assert_nothing_raised(ActiveRecord::StatementInvalid) { Topic.scoped(:offset => "3").all }
+ assert_nothing_raised(ActiveRecord::StatementInvalid) { Topic.all.merge!(:offset => "3").to_a }
end
protected
diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb
index afff020561..4c6d4666ed 100644
--- a/activerecord/test/cases/helper.rb
+++ b/activerecord/test/cases/helper.rb
@@ -5,10 +5,9 @@ require 'config'
gem 'minitest'
require 'minitest/autorun'
require 'stringio'
-require 'mocha'
-require 'cases/test_case'
require 'active_record'
+require 'cases/test_case'
require 'active_support/dependencies'
require 'active_support/logger'
@@ -20,9 +19,6 @@ require 'support/connection'
# Show backtraces for deprecated behavior for quicker cleanup.
ActiveSupport::Deprecation.debug = true
-# Avoid deprecation warning setting dependent_restrict_raises to false. The default is true
-ActiveRecord::Base.dependent_restrict_raises = false
-
# Connect to the database
ARTest.connect
diff --git a/activerecord/test/cases/inclusion_test.rb b/activerecord/test/cases/inclusion_test.rb
index 8726ba5e51..8f095e4953 100644
--- a/activerecord/test/cases/inclusion_test.rb
+++ b/activerecord/test/cases/inclusion_test.rb
@@ -4,7 +4,7 @@ require 'models/teapot'
class BasicInclusionModelTest < ActiveRecord::TestCase
def test_basic_model
Teapot.create!(:name => "Ronnie Kemper")
- assert_equal "Ronnie Kemper", Teapot.find(1).name
+ assert_equal "Ronnie Kemper", Teapot.first.name
end
def test_initialization
@@ -84,8 +84,10 @@ class InclusionUnitTest < ActiveRecord::TestCase
end
def test_deprecation_proxy
- assert_equal ActiveRecord::Model.name, ActiveRecord::Model::DeprecationProxy.name
- assert_equal ActiveRecord::Base.superclass, assert_deprecated { ActiveRecord::Model::DeprecationProxy.superclass }
+ proxy = ActiveRecord::Model::DeprecationProxy.new
+
+ assert_equal ActiveRecord::Model.name, proxy.name
+ assert_equal ActiveRecord::Base.superclass, assert_deprecated { proxy.superclass }
sup, sup2 = nil, nil
ActiveSupport.on_load(:__test_active_record_model_deprecation) do
@@ -93,11 +95,29 @@ class InclusionUnitTest < ActiveRecord::TestCase
sup2 = send(:superclass)
end
assert_deprecated do
- ActiveSupport.run_load_hooks(:__test_active_record_model_deprecation, ActiveRecord::Model::DeprecationProxy)
+ ActiveSupport.run_load_hooks(:__test_active_record_model_deprecation, proxy)
end
assert_equal ActiveRecord::Base.superclass, sup
assert_equal ActiveRecord::Base.superclass, sup2
end
+
+ test "including in deprecation proxy" do
+ model, base = ActiveRecord::Model.dup, ActiveRecord::Base.dup
+ proxy = ActiveRecord::Model::DeprecationProxy.new(model, base)
+
+ mod = Module.new
+ proxy.include mod
+ assert model < mod
+ end
+
+ test "extending in deprecation proxy" do
+ model, base = ActiveRecord::Model.dup, ActiveRecord::Base.dup
+ proxy = ActiveRecord::Model::DeprecationProxy.new(model, base)
+
+ mod = Module.new
+ assert_deprecated { proxy.extend mod }
+ assert base.singleton_class < mod
+ end
end
class InclusionFixturesTest < ActiveRecord::TestCase
diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb
index 06de51f5cd..e80259a7f1 100644
--- a/activerecord/test/cases/inheritance_test.rb
+++ b/activerecord/test/cases/inheritance_test.rb
@@ -1,7 +1,10 @@
require "cases/helper"
require 'models/company'
+require 'models/person'
+require 'models/post'
require 'models/project'
require 'models/subscriber'
+require 'models/teapot'
class InheritanceTest < ActiveRecord::TestCase
fixtures :companies, :projects, :subscribers, :accounts
@@ -24,7 +27,7 @@ class InheritanceTest < ActiveRecord::TestCase
end
})
company.save!
- company = Company.all.find { |x| x.id == company.id }
+ company = Company.all.to_a.find { |x| x.id == company.id }
assert_equal ' ', company.type
end
@@ -70,6 +73,33 @@ class InheritanceTest < ActiveRecord::TestCase
assert !Class.new(Company).descends_from_active_record?, 'Company subclass should not descend from ActiveRecord::Base'
end
+ def test_inheritance_base_class
+ assert_equal Post, Post.base_class
+ assert_equal Post, SpecialPost.base_class
+ assert_equal Post, StiPost.base_class
+ assert_equal SubStiPost, SubStiPost.base_class
+ end
+
+ def test_active_record_model_included_base_class
+ assert_equal Teapot, Teapot.base_class
+ end
+
+ def test_abstract_inheritance_base_class
+ assert_equal LoosePerson, LoosePerson.base_class
+ assert_equal LooseDescendant, LooseDescendant.base_class
+ assert_equal TightPerson, TightPerson.base_class
+ assert_equal TightPerson, TightDescendant.base_class
+ end
+
+ def test_base_class_activerecord_error
+ klass = Class.new {
+ extend ActiveRecord::Configuration
+ include ActiveRecord::Inheritance
+ }
+
+ assert_raise(ActiveRecord::ActiveRecordError) { klass.base_class }
+ end
+
def test_a_bad_type_column
#SQLServer need to turn Identity Insert On before manually inserting into the Identity column
if current_adapter?(:SybaseAdapter)
@@ -98,7 +128,7 @@ class InheritanceTest < ActiveRecord::TestCase
end
def test_inheritance_find_all
- companies = Company.scoped(:order => 'id').all
+ companies = Company.all.merge!(:order => 'id').to_a
assert_kind_of Firm, companies[0], "37signals should be a firm"
assert_kind_of Client, companies[1], "Summit should be a client"
end
@@ -149,9 +179,9 @@ class InheritanceTest < ActiveRecord::TestCase
def test_update_all_within_inheritance
Client.update_all "name = 'I am a client'"
- assert_equal "I am a client", Client.all.first.name
+ assert_equal "I am a client", Client.first.name
# Order by added as otherwise Oracle tests were failing because of different order of results
- assert_equal "37signals", Firm.scoped(:order => "id").all.first.name
+ assert_equal "37signals", Firm.all.merge!(:order => "id").to_a.first.name
end
def test_alt_update_all_within_inheritance
@@ -173,9 +203,9 @@ class InheritanceTest < ActiveRecord::TestCase
end
def test_find_first_within_inheritance
- assert_kind_of Firm, Company.scoped(:where => "name = '37signals'").first
- assert_kind_of Firm, Firm.scoped(:where => "name = '37signals'").first
- assert_nil Client.scoped(:where => "name = '37signals'").first
+ assert_kind_of Firm, Company.all.merge!(:where => "name = '37signals'").first
+ assert_kind_of Firm, Firm.all.merge!(:where => "name = '37signals'").first
+ assert_nil Client.all.merge!(:where => "name = '37signals'").first
end
def test_alt_find_first_within_inheritance
@@ -187,10 +217,10 @@ class InheritanceTest < ActiveRecord::TestCase
def test_complex_inheritance
very_special_client = VerySpecialClient.create("name" => "veryspecial")
assert_equal very_special_client, VerySpecialClient.where("name = 'veryspecial'").first
- assert_equal very_special_client, SpecialClient.scoped(:where => "name = 'veryspecial'").first
- assert_equal very_special_client, Company.scoped(:where => "name = 'veryspecial'").first
- assert_equal very_special_client, Client.scoped(:where => "name = 'veryspecial'").first
- assert_equal 1, Client.scoped(:where => "name = 'Summit'").all.size
+ assert_equal very_special_client, SpecialClient.all.merge!(:where => "name = 'veryspecial'").first
+ assert_equal very_special_client, Company.all.merge!(:where => "name = 'veryspecial'").first
+ assert_equal very_special_client, Client.all.merge!(:where => "name = 'veryspecial'").first
+ assert_equal 1, Client.all.merge!(:where => "name = 'Summit'").to_a.size
assert_equal very_special_client, Client.find(very_special_client.id)
end
@@ -201,14 +231,14 @@ class InheritanceTest < ActiveRecord::TestCase
end
def test_eager_load_belongs_to_something_inherited
- account = Account.scoped(:includes => :firm).find(1)
+ account = Account.all.merge!(:includes => :firm).find(1)
assert account.association_cache.key?(:firm), "nil proves eager load failed"
end
def test_eager_load_belongs_to_primary_key_quoting
con = Account.connection
assert_sql(/#{con.quote_table_name('companies')}.#{con.quote_column_name('id')} IN \(1\)/) do
- Account.scoped(:includes => :firm).find(1)
+ Account.all.merge!(:includes => :firm).find(1)
end
end
@@ -230,7 +260,7 @@ class InheritanceTest < ActiveRecord::TestCase
private
def switch_to_alt_inheritance_column
# we don't want misleading test results, so get rid of the values in the type column
- Company.scoped(:order => 'id').all.each do |c|
+ Company.all.merge!(:order => 'id').to_a.each do |c|
c['type'] = nil
c.save
end
diff --git a/activerecord/test/cases/json_serialization_test.rb b/activerecord/test/cases/json_serialization_test.rb
index d9e350abc0..a86b165c78 100644
--- a/activerecord/test/cases/json_serialization_test.rb
+++ b/activerecord/test/cases/json_serialization_test.rb
@@ -83,6 +83,53 @@ class JsonSerializationTest < ActiveRecord::TestCase
assert_match %r{"favorite_quote":"Constraints are liberating"}, methods_json
end
+ def test_uses_serializable_hash_with_only_option
+ def @contact.serializable_hash(options=nil)
+ super(only: %w(name))
+ end
+
+ json = @contact.to_json
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_no_match %r{awesome}, json
+ assert_no_match %r{age}, json
+ end
+
+ def test_uses_serializable_hash_with_except_option
+ def @contact.serializable_hash(options=nil)
+ super(except: %w(age))
+ end
+
+ json = @contact.to_json
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_match %r{"awesome":true}, json
+ assert_no_match %r{age}, json
+ end
+
+ def test_does_not_include_inheritance_column_from_sti
+ @contact = ContactSti.new(@contact.attributes)
+ assert_equal 'ContactSti', @contact.type
+
+ json = @contact.to_json
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_no_match %r{type}, json
+ assert_no_match %r{ContactSti}, json
+ end
+
+ def test_serializable_hash_with_default_except_option_and_excluding_inheritance_column_from_sti
+ @contact = ContactSti.new(@contact.attributes)
+ assert_equal 'ContactSti', @contact.type
+
+ def @contact.serializable_hash(options={})
+ super({ except: %w(age) }.merge!(options))
+ end
+
+ json = @contact.to_json
+ assert_match %r{"name":"Konata Izumi"}, json
+ assert_no_match %r{age}, json
+ assert_no_match %r{type}, json
+ assert_no_match %r{ContactSti}, json
+ end
+
def test_serializable_hash_should_not_modify_options_in_argument
options = { :only => :name }
@contact.serializable_hash(options)
diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb
index afb0bd6fd9..2392516395 100644
--- a/activerecord/test/cases/locking_test.rb
+++ b/activerecord/test/cases/locking_test.rb
@@ -3,6 +3,7 @@ require "cases/helper"
require 'models/person'
require 'models/job'
require 'models/reader'
+require 'models/ship'
require 'models/legacy_thing'
require 'models/reference'
require 'models/string_key_object'
@@ -18,8 +19,8 @@ class LockWithCustomColumnWithoutDefault < ActiveRecord::Base
self.locking_column = :custom_lock_version
end
-class ReadonlyFirstNamePerson < Person
- attr_readonly :first_name
+class ReadonlyNameShip < Ship
+ attr_readonly :name
end
class OptimisticLockingTest < ActiveRecord::TestCase
@@ -200,15 +201,15 @@ class OptimisticLockingTest < ActiveRecord::TestCase
end
def test_readonly_attributes
- assert_equal Set.new([ 'first_name' ]), ReadonlyFirstNamePerson.readonly_attributes
+ assert_equal Set.new([ 'name' ]), ReadonlyNameShip.readonly_attributes
- p = ReadonlyFirstNamePerson.create(:first_name => "unchangeable name")
- p.reload
- assert_equal "unchangeable name", p.first_name
+ s = ReadonlyNameShip.create(:name => "unchangeable name")
+ s.reload
+ assert_equal "unchangeable name", s.name
- p.update_attributes(:first_name => "changed name")
- p.reload
- assert_equal "unchangeable name", p.first_name
+ s.update_attributes(:name => "changed name")
+ s.reload
+ assert_equal "unchangeable name", s.name
end
def test_quote_table_name
diff --git a/activerecord/test/cases/log_subscriber_test.rb b/activerecord/test/cases/log_subscriber_test.rb
index acd2fcdad4..70d00aecf9 100644
--- a/activerecord/test/cases/log_subscriber_test.rb
+++ b/activerecord/test/cases/log_subscriber_test.rb
@@ -54,7 +54,7 @@ class LogSubscriberTest < ActiveRecord::TestCase
end
def test_basic_query_logging
- Developer.all
+ Developer.all.load
wait
assert_equal 1, @logger.logged(:debug).size
assert_match(/Developer Load/, @logger.logged(:debug).last)
@@ -71,8 +71,8 @@ class LogSubscriberTest < ActiveRecord::TestCase
def test_cached_queries
ActiveRecord::Base.cache do
- Developer.all
- Developer.all
+ Developer.all.load
+ Developer.all.load
end
wait
assert_equal 2, @logger.logged(:debug).size
@@ -82,7 +82,7 @@ class LogSubscriberTest < ActiveRecord::TestCase
def test_basic_query_doesnt_log_when_level_is_not_debug
@logger.level = INFO
- Developer.all
+ Developer.all.load
wait
assert_equal 0, @logger.logged(:debug).size
end
@@ -90,8 +90,8 @@ class LogSubscriberTest < ActiveRecord::TestCase
def test_cached_queries_doesnt_log_when_level_is_not_debug
@logger.level = INFO
ActiveRecord::Base.cache do
- Developer.all
- Developer.all
+ Developer.all.load
+ Developer.all.load
end
wait
assert_equal 0, @logger.logged(:debug).size
diff --git a/activerecord/test/cases/mass_assignment_security_test.rb b/activerecord/test/cases/mass_assignment_security_test.rb
index 2f98d3c646..a36b2c2506 100644
--- a/activerecord/test/cases/mass_assignment_security_test.rb
+++ b/activerecord/test/cases/mass_assignment_security_test.rb
@@ -95,7 +95,11 @@ class MassAssignmentSecurityTest < ActiveRecord::TestCase
end
def test_mass_assigning_does_not_choke_on_nil
- Firm.new.assign_attributes(nil)
+ assert_nil Firm.new.assign_attributes(nil)
+ end
+
+ def test_mass_assigning_does_not_choke_on_empty_hash
+ assert_nil Firm.new.assign_attributes({})
end
def test_assign_attributes_uses_default_role_when_no_role_is_provided
@@ -247,10 +251,69 @@ class MassAssignmentSecurityTest < ActiveRecord::TestCase
assert !Task.new.respond_to?("#{method}=")
end
end
+
+ test "ActiveRecord::Model.whitelist_attributes works for models which include Model" do
+ begin
+ prev, ActiveRecord::Model.whitelist_attributes = ActiveRecord::Model.whitelist_attributes, true
+
+ klass = Class.new { include ActiveRecord::Model }
+ assert_equal ActiveModel::MassAssignmentSecurity::WhiteList, klass.active_authorizers[:default].class
+ assert_equal [], klass.active_authorizers[:default].to_a
+ ensure
+ ActiveRecord::Model.whitelist_attributes = prev
+ end
+ end
+
+ test "ActiveRecord::Model.whitelist_attributes works for models which inherit Base" do
+ begin
+ prev, ActiveRecord::Model.whitelist_attributes = ActiveRecord::Model.whitelist_attributes, true
+
+ klass = Class.new(ActiveRecord::Base)
+ assert_equal ActiveModel::MassAssignmentSecurity::WhiteList, klass.active_authorizers[:default].class
+ assert_equal [], klass.active_authorizers[:default].to_a
+
+ klass.attr_accessible 'foo'
+ assert_equal ['foo'], Class.new(klass).active_authorizers[:default].to_a
+ ensure
+ ActiveRecord::Model.whitelist_attributes = prev
+ end
+ end
+
+ test "ActiveRecord::Model.mass_assignment_sanitizer works for models which include Model" do
+ begin
+ sanitizer = Object.new
+ prev, ActiveRecord::Model.mass_assignment_sanitizer = ActiveRecord::Model.mass_assignment_sanitizer, sanitizer
+
+ klass = Class.new { include ActiveRecord::Model }
+ assert_equal sanitizer, klass._mass_assignment_sanitizer
+
+ ActiveRecord::Model.mass_assignment_sanitizer = nil
+ klass = Class.new { include ActiveRecord::Model }
+ assert_not_nil klass._mass_assignment_sanitizer
+ ensure
+ ActiveRecord::Model.mass_assignment_sanitizer = prev
+ end
+ end
+
+ test "ActiveRecord::Model.mass_assignment_sanitizer works for models which inherit Base" do
+ begin
+ sanitizer = Object.new
+ prev, ActiveRecord::Model.mass_assignment_sanitizer = ActiveRecord::Model.mass_assignment_sanitizer, sanitizer
+
+ klass = Class.new(ActiveRecord::Base)
+ assert_equal sanitizer, klass._mass_assignment_sanitizer
+
+ sanitizer2 = Object.new
+ klass.mass_assignment_sanitizer = sanitizer2
+ assert_equal sanitizer2, Class.new(klass)._mass_assignment_sanitizer
+ ensure
+ ActiveRecord::Model.mass_assignment_sanitizer = prev
+ end
+ end
end
-# This class should be deleted when we removed active_record_deprecated_finders as a
+# This class should be deleted when we remove activerecord-deprecated_finders as a
# dependency.
class MassAssignmentSecurityDeprecatedFindersTest < ActiveRecord::TestCase
include MassAssignmentTestHelpers
@@ -878,4 +941,26 @@ class MassAssignmentSecurityNestedAttributesTest < ActiveRecord::TestCase
assert_all_attributes(person.best_friends.first)
end
+ def test_mass_assignment_options_are_reset_after_exception
+ person = NestedPerson.create!({ :first_name => 'David', :gender => 'm' }, :as => :admin)
+ person.create_best_friend!({ :first_name => 'Jeremy', :gender => 'm' }, :as => :admin)
+
+ attributes = { :best_friend_attributes => { :comments => 'rides a sweet bike' } }
+ assert_raises(RuntimeError) { person.assign_attributes(attributes, :as => :admin) }
+ assert_equal 'm', person.best_friend.gender
+
+ person.best_friend_attributes = { :gender => 'f' }
+ assert_equal 'm', person.best_friend.gender
+ end
+
+ def test_mass_assignment_options_are_nested_correctly
+ person = NestedPerson.create!({ :first_name => 'David', :gender => 'm' }, :as => :admin)
+ person.create_best_friend!({ :first_name => 'Jeremy', :gender => 'm' }, :as => :admin)
+
+ attributes = { :best_friend_first_name => 'Josh', :best_friend_attributes => { :gender => 'f' } }
+ person.assign_attributes(attributes, :as => :admin)
+ assert_equal 'Josh', person.best_friend.first_name
+ assert_equal 'f', person.best_friend.gender
+ end
+
end
diff --git a/activerecord/test/cases/migration/change_schema_test.rb b/activerecord/test/cases/migration/change_schema_test.rb
index ab61a4dcef..ec4c554abb 100644
--- a/activerecord/test/cases/migration/change_schema_test.rb
+++ b/activerecord/test/cases/migration/change_schema_test.rb
@@ -141,8 +141,8 @@ module ActiveRecord
created_at_column = created_columns.detect {|c| c.name == 'created_at' }
updated_at_column = created_columns.detect {|c| c.name == 'updated_at' }
- assert !created_at_column.null
- assert !updated_at_column.null
+ assert created_at_column.null
+ assert updated_at_column.null
end
def test_create_table_with_timestamps_should_create_datetime_columns_with_options
@@ -291,14 +291,20 @@ module ActiveRecord
def test_column_exists_with_definition
connection.create_table :testings do |t|
- t.column :foo, :string, :limit => 100
- t.column :bar, :decimal, :precision => 8, :scale => 2
+ t.column :foo, :string, limit: 100
+ t.column :bar, :decimal, precision: 8, scale: 2
+ t.column :taggable_id, :integer, null: false
+ t.column :taggable_type, :string, default: 'Photo'
end
- assert connection.column_exists?(:testings, :foo, :string, :limit => 100)
- refute connection.column_exists?(:testings, :foo, :string, :limit => 50)
- assert connection.column_exists?(:testings, :bar, :decimal, :precision => 8, :scale => 2)
- refute connection.column_exists?(:testings, :bar, :decimal, :precision => 10, :scale => 2)
+ assert connection.column_exists?(:testings, :foo, :string, limit: 100)
+ refute connection.column_exists?(:testings, :foo, :string, limit: nil)
+ assert connection.column_exists?(:testings, :bar, :decimal, precision: 8, scale: 2)
+ refute connection.column_exists?(:testings, :bar, :decimal, precision: nil, scale: nil)
+ assert connection.column_exists?(:testings, :taggable_id, :integer, null: false)
+ refute connection.column_exists?(:testings, :taggable_id, :integer, null: true)
+ assert connection.column_exists?(:testings, :taggable_type, :string, default: 'Photo')
+ refute connection.column_exists?(:testings, :taggable_type, :string, default: nil)
end
def test_column_exists_on_table_with_no_options_parameter_supplied
diff --git a/activerecord/test/cases/migration/change_table_test.rb b/activerecord/test/cases/migration/change_table_test.rb
index 063209389f..4614be9650 100644
--- a/activerecord/test/cases/migration/change_table_test.rb
+++ b/activerecord/test/cases/migration/change_table_test.rb
@@ -30,61 +30,57 @@ module ActiveRecord
def test_references_column_type_adds_id
with_change_table do |t|
- @connection.expect :add_column, nil, [:delete_me, 'customer_id', :integer, {}]
+ @connection.expect :add_reference, nil, [:delete_me, :customer, {}]
t.references :customer
end
end
def test_remove_references_column_type_removes_id
with_change_table do |t|
- @connection.expect :remove_column, nil, [:delete_me, 'customer_id']
+ @connection.expect :remove_reference, nil, [:delete_me, :customer, {}]
t.remove_references :customer
end
end
def test_add_belongs_to_works_like_add_references
with_change_table do |t|
- @connection.expect :add_column, nil, [:delete_me, 'customer_id', :integer, {}]
+ @connection.expect :add_reference, nil, [:delete_me, :customer, {}]
t.belongs_to :customer
end
end
def test_remove_belongs_to_works_like_remove_references
with_change_table do |t|
- @connection.expect :remove_column, nil, [:delete_me, 'customer_id']
+ @connection.expect :remove_reference, nil, [:delete_me, :customer, {}]
t.remove_belongs_to :customer
end
end
def test_references_column_type_with_polymorphic_adds_type
with_change_table do |t|
- @connection.expect :add_column, nil, [:delete_me, 'taggable_id', :integer, {}]
- @connection.expect :add_column, nil, [:delete_me, 'taggable_type', :string, {}]
- t.references :taggable, :polymorphic => true
+ @connection.expect :add_reference, nil, [:delete_me, :taggable, polymorphic: true]
+ t.references :taggable, polymorphic: true
end
end
def test_remove_references_column_type_with_polymorphic_removes_type
with_change_table do |t|
- @connection.expect :remove_column, nil, [:delete_me, 'taggable_id']
- @connection.expect :remove_column, nil, [:delete_me, 'taggable_type']
- t.remove_references :taggable, :polymorphic => true
+ @connection.expect :remove_reference, nil, [:delete_me, :taggable, polymorphic: true]
+ t.remove_references :taggable, polymorphic: true
end
end
def test_references_column_type_with_polymorphic_and_options_null_is_false_adds_table_flag
with_change_table do |t|
- @connection.expect :add_column, nil, [:delete_me, 'taggable_id', :integer, {:null => false}]
- @connection.expect :add_column, nil, [:delete_me, 'taggable_type', :string, {:null => false}]
- t.references :taggable, :polymorphic => true, :null => false
+ @connection.expect :add_reference, nil, [:delete_me, :taggable, polymorphic: true, null: false]
+ t.references :taggable, polymorphic: true, null: false
end
end
def test_remove_references_column_type_with_polymorphic_and_options_null_is_false_removes_table_flag
with_change_table do |t|
- @connection.expect :remove_column, nil, [:delete_me, 'taggable_id']
- @connection.expect :remove_column, nil, [:delete_me, 'taggable_type']
- t.remove_references :taggable, :polymorphic => true, :null => false
+ @connection.expect :remove_reference, nil, [:delete_me, :taggable, polymorphic: true, null: false]
+ t.remove_references :taggable, polymorphic: true, null: false
end
end
diff --git a/activerecord/test/cases/migration/column_attributes_test.rb b/activerecord/test/cases/migration/column_attributes_test.rb
index 18f8d82bfe..b88db384a0 100644
--- a/activerecord/test/cases/migration/column_attributes_test.rb
+++ b/activerecord/test/cases/migration/column_attributes_test.rb
@@ -7,6 +7,14 @@ module ActiveRecord
self.use_transactional_fixtures = false
+ def test_add_column_newline_default
+ string = "foo\nbar"
+ add_column 'test_models', 'command', :string, :default => string
+ TestModel.reset_column_information
+
+ assert_equal string, TestModel.new.command
+ end
+
def test_add_remove_single_field_using_string_arguments
refute TestModel.column_methods_hash.key?(:last_name)
@@ -54,13 +62,13 @@ module ActiveRecord
# Do a manual insertion
if current_adapter?(:OracleAdapter)
- connection.execute "insert into test_models (id, wealth, created_at, updated_at) values (people_seq.nextval, 12345678901234567890.0123456789, sysdate, sysdate)"
+ connection.execute "insert into test_models (id, wealth) values (people_seq.nextval, 12345678901234567890.0123456789)"
elsif current_adapter?(:OpenBaseAdapter) || (current_adapter?(:MysqlAdapter) && Mysql.client_version < 50003) #before mysql 5.0.3 decimals stored as strings
- connection.execute "insert into test_models (wealth, created_at, updated_at) values ('12345678901234567890.0123456789', 0, 0)"
+ connection.execute "insert into test_models (wealth) values ('12345678901234567890.0123456789')"
elsif current_adapter?(:PostgreSQLAdapter)
- connection.execute "insert into test_models (wealth, created_at, updated_at) values (12345678901234567890.0123456789, now(), now())"
+ connection.execute "insert into test_models (wealth) values (12345678901234567890.0123456789)"
else
- connection.execute "insert into test_models (wealth, created_at, updated_at) values (12345678901234567890.0123456789, 0, 0)"
+ connection.execute "insert into test_models (wealth) values (12345678901234567890.0123456789)"
end
# SELECT
@@ -174,7 +182,7 @@ module ActiveRecord
assert_not_equal "Z", bob.moment_of_truth.zone
# US/Eastern is -5 hours from GMT
assert_equal Rational(-5, 24), bob.moment_of_truth.offset
- assert_match(/\A-05:?00\Z/, bob.moment_of_truth.zone) #ruby 1.8.6 uses HH:MM, prior versions use HHMM
+ assert_match(/\A-05:00\Z/, bob.moment_of_truth.zone)
assert_equal DateTime::ITALY, bob.moment_of_truth.start
end
end
diff --git a/activerecord/test/cases/migration/command_recorder_test.rb b/activerecord/test/cases/migration/command_recorder_test.rb
index 7d026961be..f2213ee6aa 100644
--- a/activerecord/test/cases/migration/command_recorder_test.rb
+++ b/activerecord/test/cases/migration/command_recorder_test.rb
@@ -110,9 +110,9 @@ module ActiveRecord
end
def test_invert_add_index_with_name
- @recorder.record :add_index, [:table, [:one, :two], {:name => "new_index"}]
- remove = @recorder.inverse.first
- assert_equal [:remove_index, [:table, {:name => "new_index"}]], remove
+ @recorder.record :add_index, [:table, [:one, :two], {:name => "new_index"}]
+ remove = @recorder.inverse.first
+ assert_equal [:remove_index, [:table, {:name => "new_index"}]], remove
end
def test_invert_add_index_with_no_options
@@ -138,6 +138,30 @@ module ActiveRecord
add = @recorder.inverse.first
assert_equal [:add_timestamps, [:table]], add
end
+
+ def test_invert_add_reference
+ @recorder.record :add_reference, [:table, :taggable, { polymorphic: true }]
+ remove = @recorder.inverse.first
+ assert_equal [:remove_reference, [:table, :taggable, { polymorphic: true }]], remove
+ end
+
+ def test_invert_add_belongs_to_alias
+ @recorder.record :add_belongs_to, [:table, :user]
+ remove = @recorder.inverse.first
+ assert_equal [:remove_reference, [:table, :user]], remove
+ end
+
+ def test_invert_remove_reference
+ @recorder.record :remove_reference, [:table, :taggable, { polymorphic: true }]
+ add = @recorder.inverse.first
+ assert_equal [:add_reference, [:table, :taggable, { polymorphic: true }]], add
+ end
+
+ def test_invert_remove_belongs_to_alias
+ @recorder.record :remove_belongs_to, [:table, :user]
+ add = @recorder.inverse.first
+ assert_equal [:add_reference, [:table, :user]], add
+ end
end
end
end
diff --git a/activerecord/test/cases/migration/create_join_table_test.rb b/activerecord/test/cases/migration/create_join_table_test.rb
index 0428d9ba76..cd1b0e8b47 100644
--- a/activerecord/test/cases/migration/create_join_table_test.rb
+++ b/activerecord/test/cases/migration/create_join_table_test.rb
@@ -10,60 +10,67 @@ module ActiveRecord
@connection = ActiveRecord::Base.connection
end
+ def teardown
+ super
+ %w(artists_musics musics_videos catalog).each do |table_name|
+ connection.drop_table table_name if connection.tables.include?(table_name)
+ end
+ end
+
def test_create_join_table
connection.create_join_table :artists, :musics
assert_equal %w(artist_id music_id), connection.columns(:artists_musics).map(&:name).sort
- ensure
- connection.drop_table :artists_musics
end
def test_create_join_table_set_not_null_by_default
connection.create_join_table :artists, :musics
assert_equal [false, false], connection.columns(:artists_musics).map(&:null)
- ensure
- connection.drop_table :artists_musics
end
def test_create_join_table_with_strings
connection.create_join_table 'artists', 'musics'
assert_equal %w(artist_id music_id), connection.columns(:artists_musics).map(&:name).sort
- ensure
- connection.drop_table :artists_musics
end
def test_create_join_table_with_the_proper_order
connection.create_join_table :videos, :musics
assert_equal %w(music_id video_id), connection.columns(:musics_videos).map(&:name).sort
- ensure
- connection.drop_table :musics_videos
end
def test_create_join_table_with_the_table_name
- connection.create_join_table :artists, :musics, :table_name => :catalog
+ connection.create_join_table :artists, :musics, table_name: :catalog
assert_equal %w(artist_id music_id), connection.columns(:catalog).map(&:name).sort
- ensure
- connection.drop_table :catalog
end
def test_create_join_table_with_the_table_name_as_string
- connection.create_join_table :artists, :musics, :table_name => 'catalog'
+ connection.create_join_table :artists, :musics, table_name: 'catalog'
assert_equal %w(artist_id music_id), connection.columns(:catalog).map(&:name).sort
- ensure
- connection.drop_table :catalog
end
def test_create_join_table_with_column_options
- connection.create_join_table :artists, :musics, :column_options => {:null => true}
+ connection.create_join_table :artists, :musics, column_options: {null: true}
assert_equal [true, true], connection.columns(:artists_musics).map(&:null)
- ensure
- connection.drop_table :artists_musics
+ end
+
+ def test_create_join_table_without_indexes
+ connection.create_join_table :artists, :musics
+
+ assert connection.indexes(:artists_musics).blank?
+ end
+
+ def test_create_join_table_with_index
+ connection.create_join_table :artists, :musics do |t|
+ t.index [:artist_id, :music_id]
+ end
+
+ assert_equal [%w(artist_id music_id)], connection.indexes(:artists_musics).map(&:columns)
end
end
end
diff --git a/activerecord/test/cases/migration/helper.rb b/activerecord/test/cases/migration/helper.rb
index fe53510ba2..768ebc5861 100644
--- a/activerecord/test/cases/migration/helper.rb
+++ b/activerecord/test/cases/migration/helper.rb
@@ -14,8 +14,10 @@ module ActiveRecord
module TestHelper
attr_reader :connection, :table_name
+ CONNECTION_METHODS = %w[add_column remove_column rename_column add_index change_column rename_table column_exists? index_exists? add_reference add_belongs_to remove_reference remove_references remove_belongs_to]
+
class TestModel < ActiveRecord::Base
- self.table_name = 'test_models'
+ self.table_name = :test_models
end
def setup
@@ -36,29 +38,8 @@ module ActiveRecord
end
private
- def add_column(*args)
- connection.add_column(*args)
- end
-
- def remove_column(*args)
- connection.remove_column(*args)
- end
-
- def rename_column(*args)
- connection.rename_column(*args)
- end
- def add_index(*args)
- connection.add_index(*args)
- end
-
- def change_column(*args)
- connection.change_column(*args)
- end
-
- def rename_table(*args)
- connection.rename_table(*args)
- end
+ delegate(*CONNECTION_METHODS, to: :connection)
end
end
end
diff --git a/activerecord/test/cases/migration/references_index_test.rb b/activerecord/test/cases/migration/references_index_test.rb
index 8ab1c59724..264a99f9ce 100644
--- a/activerecord/test/cases/migration/references_index_test.rb
+++ b/activerecord/test/cases/migration/references_index_test.rb
@@ -51,6 +51,8 @@ module ActiveRecord
end
def test_creates_polymorphic_index
+ return skip "Oracle Adapter does not support foreign keys if :polymorphic => true is used" if current_adapter? :OracleAdapter
+
connection.create_table table_name do |t|
t.references :foo, :polymorphic => true, :index => true
end
@@ -86,6 +88,7 @@ module ActiveRecord
end
def test_creates_polymorphic_index_for_existing_table
+ return skip "Oracle Adapter does not support foreign keys if :polymorphic => true is used" if current_adapter? :OracleAdapter
connection.create_table table_name
connection.change_table table_name do |t|
t.references :foo, :polymorphic => true, :index => true
diff --git a/activerecord/test/cases/migration/references_statements_test.rb b/activerecord/test/cases/migration/references_statements_test.rb
new file mode 100644
index 0000000000..144302bd4a
--- /dev/null
+++ b/activerecord/test/cases/migration/references_statements_test.rb
@@ -0,0 +1,111 @@
+require "cases/migration/helper"
+
+module ActiveRecord
+ class Migration
+ class ReferencesStatementsTest < ActiveRecord::TestCase
+ include ActiveRecord::Migration::TestHelper
+
+ self.use_transactional_fixtures = false
+
+ def setup
+ super
+ @table_name = :test_models
+
+ add_column table_name, :supplier_id, :integer
+ add_index table_name, :supplier_id
+ end
+
+ def test_creates_reference_id_column
+ add_reference table_name, :user
+ assert column_exists?(table_name, :user_id, :integer)
+ end
+
+ def test_does_not_create_reference_type_column
+ add_reference table_name, :taggable
+ refute column_exists?(table_name, :taggable_type, :string)
+ end
+
+ def test_creates_reference_type_column
+ add_reference table_name, :taggable, polymorphic: true
+ assert column_exists?(table_name, :taggable_type, :string)
+ end
+
+ def test_creates_reference_id_index
+ add_reference table_name, :user, index: true
+ assert index_exists?(table_name, :user_id)
+ end
+
+ def test_does_not_create_reference_id_index
+ add_reference table_name, :user
+ refute index_exists?(table_name, :user_id)
+ end
+
+ def test_creates_polymorphic_index
+ add_reference table_name, :taggable, polymorphic: true, index: true
+ assert index_exists?(table_name, [:taggable_id, :taggable_type])
+ end
+
+ def test_creates_reference_type_column_with_default
+ add_reference table_name, :taggable, polymorphic: { default: 'Photo' }, index: true
+ assert column_exists?(table_name, :taggable_type, :string, default: 'Photo')
+ end
+
+ def test_creates_named_index
+ add_reference table_name, :tag, index: { name: 'index_taggings_on_tag_id' }
+ assert index_exists?(table_name, :tag_id, name: 'index_taggings_on_tag_id')
+ end
+
+ def test_deletes_reference_id_column
+ remove_reference table_name, :supplier
+ refute column_exists?(table_name, :supplier_id, :integer)
+ end
+
+ def test_deletes_reference_id_index
+ remove_reference table_name, :supplier
+ refute index_exists?(table_name, :supplier_id)
+ end
+
+ def test_does_not_delete_reference_type_column
+ with_polymorphic_column do
+ remove_reference table_name, :supplier
+
+ refute column_exists?(table_name, :supplier_id, :integer)
+ assert column_exists?(table_name, :supplier_type, :string)
+ end
+ end
+
+ def test_deletes_reference_type_column
+ with_polymorphic_column do
+ remove_reference table_name, :supplier, polymorphic: true
+ refute column_exists?(table_name, :supplier_type, :string)
+ end
+ end
+
+ def test_deletes_polymorphic_index
+ with_polymorphic_column do
+ remove_reference table_name, :supplier, polymorphic: true
+ refute index_exists?(table_name, [:supplier_id, :supplier_type])
+ end
+ end
+
+ def test_add_belongs_to_alias
+ add_belongs_to table_name, :user
+ assert column_exists?(table_name, :user_id, :integer)
+ end
+
+ def test_remove_belongs_to_alias
+ remove_belongs_to table_name, :supplier
+ refute column_exists?(table_name, :supplier_id, :integer)
+ end
+
+ private
+
+ def with_polymorphic_column
+ add_column table_name, :supplier_type, :string
+ add_index table_name, [:supplier_id, :supplier_type]
+
+ yield
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/migration/rename_table_test.rb b/activerecord/test/cases/migration/rename_table_test.rb
index d5ff2c607f..21901bec3c 100644
--- a/activerecord/test/cases/migration/rename_table_test.rb
+++ b/activerecord/test/cases/migration/rename_table_test.rb
@@ -14,6 +14,11 @@ module ActiveRecord
remove_column 'test_models', :updated_at
end
+ def teardown
+ rename_table :octopi, :test_models if connection.table_exists? :octopi
+ super
+ end
+
def test_rename_table_for_sqlite_should_work_with_reserved_words
renamed = false
@@ -26,8 +31,7 @@ module ActiveRecord
renamed = true
# Using explicit id in insert for compatibility across all databases
- con = connection
- con.execute "INSERT INTO 'references' (url, created_at, updated_at) VALUES ('http://rubyonrails.com', 0, 0)"
+ connection.execute "INSERT INTO 'references' (url, created_at, updated_at) VALUES ('http://rubyonrails.com', 0, 0)"
assert_equal 'http://rubyonrails.com', connection.select_value("SELECT url FROM 'references' WHERE id=1")
ensure
return unless renamed
@@ -39,16 +43,13 @@ module ActiveRecord
rename_table :test_models, :octopi
# Using explicit id in insert for compatibility across all databases
- con = connection
- con.enable_identity_insert("octopi", true) if current_adapter?(:SybaseAdapter)
+ connection.enable_identity_insert("octopi", true) if current_adapter?(:SybaseAdapter)
- con.execute "INSERT INTO octopi (#{con.quote_column_name('id')}, #{con.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')"
+ connection.execute "INSERT INTO octopi (#{connection.quote_column_name('id')}, #{connection.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')"
- con.enable_identity_insert("octopi", false) if current_adapter?(:SybaseAdapter)
+ connection.enable_identity_insert("octopi", false) if current_adapter?(:SybaseAdapter)
assert_equal 'http://www.foreverflying.com/octopus-black7.jpg', connection.select_value("SELECT url FROM octopi WHERE id=1")
-
- rename_table :octopi, :test_models
end
def test_rename_table_with_an_index
@@ -57,15 +58,22 @@ module ActiveRecord
rename_table :test_models, :octopi
# Using explicit id in insert for compatibility across all databases
- con = ActiveRecord::Base.connection
- con.enable_identity_insert("octopi", true) if current_adapter?(:SybaseAdapter)
- con.execute "INSERT INTO octopi (#{con.quote_column_name('id')}, #{con.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')"
- con.enable_identity_insert("octopi", false) if current_adapter?(:SybaseAdapter)
+ connection.enable_identity_insert("octopi", true) if current_adapter?(:SybaseAdapter)
+ connection.execute "INSERT INTO octopi (#{connection.quote_column_name('id')}, #{connection.quote_column_name('url')}) VALUES (1, 'http://www.foreverflying.com/octopus-black7.jpg')"
+ connection.enable_identity_insert("octopi", false) if current_adapter?(:SybaseAdapter)
assert_equal 'http://www.foreverflying.com/octopus-black7.jpg', connection.select_value("SELECT url FROM octopi WHERE id=1")
assert connection.indexes(:octopi).first.columns.include?("url")
+ end
+
+ def test_rename_table_for_postgresql_should_also_rename_default_sequence
+ skip 'not supported' unless current_adapter?(:PostgreSQLAdapter)
+
+ rename_table :test_models, :octopi
+
+ pk, seq = connection.pk_and_sequence_for('octopi')
- rename_table :octopi, :test_models
+ assert_equal "octopi_#{pk}_seq", seq
end
end
end
diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb
index 5d1bad0d54..3c0d2b18d9 100644
--- a/activerecord/test/cases/migration_test.rb
+++ b/activerecord/test/cases/migration_test.rb
@@ -56,6 +56,21 @@ class MigrationTest < ActiveRecord::TestCase
Person.reset_column_information
end
+ def test_migrator_versions
+ migrations_path = MIGRATIONS_ROOT + "/valid"
+ ActiveRecord::Migrator.migrations_paths = migrations_path
+
+ ActiveRecord::Migrator.up(migrations_path)
+ assert_equal 3, ActiveRecord::Migrator.current_version
+ assert_equal 3, ActiveRecord::Migrator.last_version
+ assert_equal false, ActiveRecord::Migrator.needs_migration?
+
+ ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid")
+ assert_equal 0, ActiveRecord::Migrator.current_version
+ assert_equal 3, ActiveRecord::Migrator.last_version
+ assert_equal true, ActiveRecord::Migrator.needs_migration?
+ end
+
def test_create_table_with_force_true_does_not_drop_nonexisting_table
if Person.connection.table_exists?(:testings2)
Person.connection.drop_table :testings2
@@ -523,7 +538,7 @@ if ActiveRecord::Base.connection.supports_bulk_alter?
# 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
+ assert_queries(3, :ignore_none => true) do
with_bulk_change_table do |t|
t.change :name, :string, :default => 'NONAME'
t.change :birthdate, :datetime
diff --git a/activerecord/test/cases/modules_test.rb b/activerecord/test/cases/modules_test.rb
index a03c4f552e..08b3408665 100644
--- a/activerecord/test/cases/modules_test.rb
+++ b/activerecord/test/cases/modules_test.rb
@@ -39,7 +39,7 @@ class ModulesTest < ActiveRecord::TestCase
end
def test_associations_spanning_cross_modules
- account = MyApplication::Billing::Account.scoped(:order => 'id').first
+ account = MyApplication::Billing::Account.all.merge!(:order => 'id').first
assert_kind_of MyApplication::Business::Firm, account.firm
assert_kind_of MyApplication::Billing::Firm, account.qualified_billing_firm
assert_kind_of MyApplication::Billing::Firm, account.unqualified_billing_firm
@@ -48,7 +48,7 @@ class ModulesTest < ActiveRecord::TestCase
end
def test_find_account_and_include_company
- account = MyApplication::Billing::Account.scoped(:includes => :firm).find(1)
+ account = MyApplication::Billing::Account.all.merge!(:includes => :firm).find(1)
assert_kind_of MyApplication::Business::Firm, account.firm
end
@@ -72,8 +72,8 @@ class ModulesTest < ActiveRecord::TestCase
clients = []
assert_nothing_raised NameError, "Should be able to resolve all class constants via reflection" do
- clients << MyApplication::Business::Client.references(:accounts).scoped(:includes => {:firm => :account}, :where => 'accounts.id IS NOT NULL').find(3)
- clients << MyApplication::Business::Client.scoped(:includes => {:firm => :account}).find(3)
+ clients << MyApplication::Business::Client.references(:accounts).merge!(:includes => {:firm => :account}, :where => 'accounts.id IS NOT NULL').find(3)
+ clients << MyApplication::Business::Client.includes(:firm => :account).find(3)
end
clients.each do |client|
diff --git a/activerecord/test/cases/multiple_db_test.rb b/activerecord/test/cases/multiple_db_test.rb
index 06d6596725..42461e8ecb 100644
--- a/activerecord/test/cases/multiple_db_test.rb
+++ b/activerecord/test/cases/multiple_db_test.rb
@@ -1,9 +1,7 @@
require "cases/helper"
require 'models/entrant'
require 'models/bird'
-
-# So we can test whether Course.connection survives a reload.
-require_dependency 'models/course'
+require 'models/course'
class MultipleDbTest < ActiveRecord::TestCase
self.use_transactional_fixtures = false
diff --git a/activerecord/test/cases/named_scope_test.rb b/activerecord/test/cases/named_scope_test.rb
index bf825c002a..bd121126e7 100644
--- a/activerecord/test/cases/named_scope_test.rb
+++ b/activerecord/test/cases/named_scope_test.rb
@@ -12,14 +12,13 @@ class NamedScopeTest < ActiveRecord::TestCase
def test_implements_enumerable
assert !Topic.all.empty?
- assert_equal Topic.all, Topic.base
- assert_equal Topic.all, Topic.base.to_a
- assert_equal Topic.first, Topic.base.first
- assert_equal Topic.all, Topic.base.map { |i| i }
+ assert_equal Topic.all.to_a, Topic.base
+ assert_equal Topic.all.to_a, Topic.base.to_a
+ assert_equal Topic.first, Topic.base.first
+ assert_equal Topic.all.to_a, Topic.base.map { |i| i }
end
def test_found_items_are_cached
- Topic.columns
all_posts = Topic.base
assert_queries(1) do
@@ -30,7 +29,7 @@ class NamedScopeTest < ActiveRecord::TestCase
def test_reload_expires_cache_of_found_items
all_posts = Topic.base
- all_posts.all
+ all_posts.to_a
new_post = Topic.create!
assert !all_posts.include?(new_post)
@@ -40,12 +39,21 @@ class NamedScopeTest < ActiveRecord::TestCase
def test_delegates_finds_and_calculations_to_the_base_class
assert !Topic.all.empty?
- assert_equal Topic.all, Topic.base.all
- assert_equal Topic.first, Topic.base.first
- assert_equal Topic.count, Topic.base.count
+ assert_equal Topic.all.to_a, Topic.base.to_a
+ assert_equal Topic.first, Topic.base.first
+ assert_equal Topic.count, Topic.base.count
assert_equal Topic.average(:replies_count), Topic.base.average(:replies_count)
end
+ def test_method_missing_priority_when_delegating
+ klazz = Class.new(ActiveRecord::Base) do
+ self.table_name = "topics"
+ scope :since, Proc.new { where('written_on >= ?', Time.now - 1.day) }
+ scope :to, Proc.new { where('written_on <= ?', Time.now) }
+ end
+ assert_equal klazz.to.since.to_a, klazz.since.to.to_a
+ end
+
def test_scope_should_respond_to_own_methods_and_methods_of_the_proxy
assert Topic.approved.respond_to?(:limit)
assert Topic.approved.respond_to?(:count)
@@ -58,9 +66,9 @@ class NamedScopeTest < ActiveRecord::TestCase
end
def test_scopes_with_options_limit_finds_to_those_matching_the_criteria_specified
- assert !Topic.scoped(:where => {:approved => true}).all.empty?
+ assert !Topic.all.merge!(:where => {:approved => true}).to_a.empty?
- assert_equal Topic.scoped(:where => {:approved => true}).all, Topic.approved
+ assert_equal Topic.all.merge!(:where => {:approved => true}).to_a, Topic.approved
assert_equal Topic.where(:approved => true).count, Topic.approved.count
end
@@ -71,8 +79,8 @@ class NamedScopeTest < ActiveRecord::TestCase
end
def test_scopes_are_composable
- assert_equal((approved = Topic.scoped(:where => {:approved => true}).all), Topic.approved)
- assert_equal((replied = Topic.scoped(:where => 'replies_count > 0').all), Topic.replied)
+ assert_equal((approved = Topic.all.merge!(:where => {:approved => true}).to_a), Topic.approved)
+ assert_equal((replied = Topic.all.merge!(:where => 'replies_count > 0').to_a), Topic.replied)
assert !(approved == replied)
assert !(approved & replied).empty?
@@ -132,14 +140,14 @@ class NamedScopeTest < ActiveRecord::TestCase
def test_active_records_have_scope_named__all__
assert !Topic.all.empty?
- assert_equal Topic.all, Topic.base
+ assert_equal Topic.all.to_a, Topic.base
end
def test_active_records_have_scope_named__scoped__
scope = Topic.where("content LIKE '%Have%'")
assert !scope.empty?
- assert_equal scope, Topic.scoped(where: "content LIKE '%Have%'")
+ assert_equal scope, Topic.all.merge!(where: "content LIKE '%Have%'")
end
def test_first_and_last_should_allow_integers_for_limit
@@ -317,14 +325,14 @@ class NamedScopeTest < ActiveRecord::TestCase
def test_chaining_should_use_latest_conditions_when_searching
# Normal hash conditions
- assert_equal Topic.where(:approved => true).to_a, Topic.rejected.approved.all
- assert_equal Topic.where(:approved => false).to_a, Topic.approved.rejected.all
+ assert_equal Topic.where(:approved => true).to_a, Topic.rejected.approved.to_a
+ assert_equal Topic.where(:approved => false).to_a, Topic.approved.rejected.to_a
# Nested hash conditions with same keys
- assert_equal [posts(:sti_comments)], Post.with_special_comments.with_very_special_comments.all
+ assert_equal [posts(:sti_comments)], Post.with_special_comments.with_very_special_comments.to_a
# Nested hash conditions with different keys
- assert_equal [posts(:sti_comments)], Post.with_special_comments.with_post(4).all.uniq
+ assert_equal [posts(:sti_comments)], Post.with_special_comments.with_post(4).to_a.uniq
end
def test_scopes_batch_finders
@@ -343,13 +351,13 @@ class NamedScopeTest < ActiveRecord::TestCase
def test_table_names_for_chaining_scopes_with_and_without_table_name_included
assert_nothing_raised do
- Comment.for_first_post.for_first_author.all
+ Comment.for_first_post.for_first_author.to_a
end
end
def test_scopes_on_relations
# Topic.replied
- approved_topics = Topic.scoped.approved.order('id DESC')
+ approved_topics = Topic.all.approved.order('id DESC')
assert_equal topics(:fourth), approved_topics.first
replied_approved_topics = approved_topics.replied
@@ -364,7 +372,7 @@ class NamedScopeTest < ActiveRecord::TestCase
def test_nested_scopes_queries_size
assert_queries(1) do
- Topic.approved.by_lifo.replied.written_before(Time.now).all
+ Topic.approved.by_lifo.replied.written_before(Time.now).to_a
end
end
@@ -375,8 +383,8 @@ class NamedScopeTest < ActiveRecord::TestCase
post = posts(:welcome)
Post.cache do
- assert_queries(1) { post.comments.containing_the_letter_e.all }
- assert_no_queries { post.comments.containing_the_letter_e.all }
+ assert_queries(1) { post.comments.containing_the_letter_e.to_a }
+ assert_no_queries { post.comments.containing_the_letter_e.to_a }
end
end
@@ -384,14 +392,14 @@ class NamedScopeTest < ActiveRecord::TestCase
post = posts(:welcome)
Post.cache do
- one = assert_queries(1) { post.comments.limit_by(1).all }
+ one = assert_queries(1) { post.comments.limit_by(1).to_a }
assert_equal 1, one.size
- two = assert_queries(1) { post.comments.limit_by(2).all }
+ two = assert_queries(1) { post.comments.limit_by(2).to_a }
assert_equal 2, two.size
- assert_no_queries { post.comments.limit_by(1).all }
- assert_no_queries { post.comments.limit_by(2).all }
+ assert_no_queries { post.comments.limit_by(1).to_a }
+ assert_no_queries { post.comments.limit_by(2).to_a }
end
end
diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb
index 0559bbbe9a..3a234f0cc1 100644
--- a/activerecord/test/cases/nested_attributes_test.rb
+++ b/activerecord/test/cases/nested_attributes_test.rb
@@ -196,7 +196,7 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
end
def test_should_raise_argument_error_if_trying_to_build_polymorphic_belongs_to
- assert_raise_with_message ArgumentError, "Cannot build association looter. Are you trying to build a polymorphic one-to-one association?" do
+ assert_raise_with_message ArgumentError, "Cannot build association `looter'. Are you trying to build a polymorphic one-to-one association?" do
Treasure.new(:name => 'pearl', :looter_attributes => {:catchphrase => "Arrr"})
end
end
@@ -781,6 +781,16 @@ module NestedAttributesOnACollectionAssociationTests
assert_nothing_raised(NoMethodError) { @pirate.save! }
end
+ def test_numeric_colum_changes_from_zero_to_no_empty_string
+ Man.accepts_nested_attributes_for(:interests)
+ Interest.validates_numericality_of(:zine_id)
+ man = Man.create(:name => 'John')
+ interest = man.interests.create(:topic=>'bar',:zine_id => 0)
+ assert interest.save
+
+ assert !man.update_attributes({:interests_attributes => { :id => interest.id, :zine_id => 'foo' }})
+ end
+
private
def association_setter
diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb
index 0933a4ff3d..72b8219782 100644
--- a/activerecord/test/cases/persistence_test.rb
+++ b/activerecord/test/cases/persistence_test.rb
@@ -55,7 +55,7 @@ class PersistencesTest < ActiveRecord::TestCase
author = authors(:david)
assert_nothing_raised do
assert_equal 1, author.posts_sorted_by_id_limited.size
- assert_equal 2, author.posts_sorted_by_id_limited.scoped(:limit => 2).all.size
+ assert_equal 2, author.posts_sorted_by_id_limited.limit(2).to_a.size
assert_equal 1, author.posts_sorted_by_id_limited.update_all([ "body = ?", "bulk update!" ])
assert_equal "bulk update!", posts(:welcome).body
assert_not_equal "bulk update!", posts(:thinking).body
@@ -120,7 +120,7 @@ class PersistencesTest < ActiveRecord::TestCase
def test_destroy_all
conditions = "author_name = 'Mary'"
- topics_by_mary = Topic.scoped(:where => conditions, :order => 'id').to_a
+ topics_by_mary = Topic.all.merge!(:where => conditions, :order => 'id').to_a
assert ! topics_by_mary.empty?
assert_difference('Topic.count', -topics_by_mary.size) do
@@ -131,7 +131,7 @@ class PersistencesTest < ActiveRecord::TestCase
end
def test_destroy_many
- clients = Client.scoped(:order => 'id').find([2, 3])
+ clients = Client.all.merge!(:order => 'id').find([2, 3])
assert_difference('Client.count', -2) do
destroyed = Client.destroy([2, 3]).sort_by(&:id)
@@ -305,6 +305,13 @@ class PersistencesTest < ActiveRecord::TestCase
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(topic.id) }
end
+ def test_destroy!
+ topic = Topic.find(1)
+ assert_equal topic, topic.destroy!, 'topic.destroy! did not return self'
+ assert topic.frozen?, 'topic not frozen after destroy!'
+ assert_raise(ActiveRecord::RecordNotFound) { Topic.find(topic.id) }
+ end
+
def test_record_not_found_exception
assert_raise(ActiveRecord::RecordNotFound) { Topic.find(99999) }
end
@@ -364,71 +371,10 @@ class PersistencesTest < ActiveRecord::TestCase
assert_raise(ActiveSupport::FrozenObjectError) { client.name = "something else" }
end
- def test_update_attribute
- assert !Topic.find(1).approved?
- Topic.find(1).update_attribute("approved", true)
- assert Topic.find(1).approved?
-
- Topic.find(1).update_attribute(:approved, false)
- assert !Topic.find(1).approved?
- end
-
def test_update_attribute_does_not_choke_on_nil
assert Topic.find(1).update_attributes(nil)
end
- def test_update_attribute_for_readonly_attribute
- minivan = Minivan.find('m1')
- assert_raises(ActiveRecord::ActiveRecordError) { minivan.update_attribute(:color, 'black') }
- end
-
- # This test is correct, but it is hard to fix it since
- # update_attribute trigger simply call save! that triggers
- # all callbacks.
- # def test_update_attribute_with_one_changed_and_one_updated
- # t = Topic.order('id').limit(1).first
- # title, author_name = t.title, t.author_name
- # t.author_name = 'John'
- # t.update_attribute(:title, 'super_title')
- # assert_equal 'John', t.author_name
- # assert_equal 'super_title', t.title
- # assert t.changed?, "topic should have changed"
- # assert t.author_name_changed?, "author_name should have changed"
- # assert !t.title_changed?, "title should not have changed"
- # assert_nil t.title_change, 'title change should be nil'
- # assert_equal ['author_name'], t.changed
- #
- # t.reload
- # assert_equal 'David', t.author_name
- # assert_equal 'super_title', t.title
- # end
-
- def test_update_attribute_with_one_updated
- t = Topic.first
- t.update_attribute(:title, 'super_title')
- assert_equal 'super_title', t.title
- assert !t.changed?, "topic should not have changed"
- assert !t.title_changed?, "title should not have changed"
- assert_nil t.title_change, 'title change should be nil'
-
- t.reload
- assert_equal 'super_title', t.title
- end
-
- def test_update_attribute_for_updated_at_on
- developer = Developer.find(1)
- prev_month = Time.now.prev_month
-
- developer.update_attribute(:updated_at, prev_month)
- assert_equal prev_month, developer.updated_at
-
- developer.update_attribute(:salary, 80001)
- assert_not_equal prev_month, developer.updated_at
-
- developer.reload
- assert_not_equal prev_month, developer.updated_at
- end
-
def test_update_column
topic = Topic.find(1)
topic.update_column("approved", true)
@@ -460,7 +406,7 @@ class PersistencesTest < ActiveRecord::TestCase
def test_update_column_should_not_leave_the_object_dirty
topic = Topic.find(1)
- topic.update_attribute("content", "Have a nice day")
+ topic.update_column("content", "Have a nice day")
topic.reload
topic.update_column(:content, "You too")
@@ -515,6 +461,97 @@ class PersistencesTest < ActiveRecord::TestCase
assert_equal 'super_title', t.title
end
+ def test_update_columns
+ topic = Topic.find(1)
+ topic.update_columns({ "approved" => true, title: "Sebastian Topic" })
+ assert topic.approved?
+ assert_equal "Sebastian Topic", topic.title
+ topic.reload
+ assert topic.approved?
+ assert_equal "Sebastian Topic", topic.title
+ end
+
+ def test_update_columns_should_not_use_setter_method
+ dev = Developer.find(1)
+ dev.instance_eval { def salary=(value); write_attribute(:salary, value * 2); end }
+
+ dev.update_columns(salary: 80000)
+ assert_equal 80000, dev.salary
+
+ dev.reload
+ assert_equal 80000, dev.salary
+ end
+
+ def test_update_columns_should_raise_exception_if_new_record
+ topic = Topic.new
+ assert_raises(ActiveRecord::ActiveRecordError) { topic.update_columns({ approved: false }) }
+ end
+
+ def test_update_columns_should_not_leave_the_object_dirty
+ topic = Topic.find(1)
+ topic.update_attributes({ "content" => "Have a nice day", :author_name => "Jose" })
+
+ topic.reload
+ topic.update_columns({ content: "You too", "author_name" => "Sebastian" })
+ assert_equal [], topic.changed
+
+ topic.reload
+ topic.update_columns({ content: "Have a nice day", author_name: "Jose" })
+ assert_equal [], topic.changed
+ end
+
+ def test_update_columns_with_model_having_primary_key_other_than_id
+ minivan = Minivan.find('m1')
+ new_name = 'sebavan'
+
+ minivan.update_columns(name: new_name)
+ assert_equal new_name, minivan.name
+ end
+
+ def test_update_columns_with_one_readonly_attribute
+ minivan = Minivan.find('m1')
+ prev_color = minivan.color
+ prev_name = minivan.name
+ assert_raises(ActiveRecord::ActiveRecordError) { minivan.update_columns({ name: "My old minivan", color: 'black' }) }
+ assert_equal prev_color, minivan.color
+ assert_equal prev_name, minivan.name
+
+ minivan.reload
+ assert_equal prev_color, minivan.color
+ assert_equal prev_name, minivan.name
+ end
+
+ def test_update_columns_should_not_modify_updated_at
+ developer = Developer.find(1)
+ prev_month = Time.now.prev_month
+
+ developer.update_columns(updated_at: prev_month)
+ assert_equal prev_month, developer.updated_at
+
+ developer.update_columns(salary: 80000)
+ assert_equal prev_month, developer.updated_at
+ assert_equal 80000, developer.salary
+
+ developer.reload
+ assert_equal prev_month.to_i, developer.updated_at.to_i
+ assert_equal 80000, developer.salary
+ end
+
+ def test_update_columns_with_one_changed_and_one_updated
+ t = Topic.order('id').limit(1).first
+ author_name = t.author_name
+ t.author_name = 'John'
+ t.update_columns(title: 'super_title')
+ assert_equal 'John', t.author_name
+ assert_equal 'super_title', t.title
+ assert t.changed?, "topic should have changed"
+ assert t.author_name_changed?, "author_name should have changed"
+
+ t.reload
+ assert_equal author_name, t.author_name
+ assert_equal 'super_title', t.title
+ end
+
def test_update_attributes
topic = Topic.find(1)
assert !topic.approved?
diff --git a/activerecord/test/cases/query_cache_test.rb b/activerecord/test/cases/query_cache_test.rb
index a712e5f689..2d778e9e90 100644
--- a/activerecord/test/cases/query_cache_test.rb
+++ b/activerecord/test/cases/query_cache_test.rb
@@ -39,6 +39,18 @@ class QueryCacheTest < ActiveRecord::TestCase
assert ActiveRecord::Base.connection.query_cache_enabled, 'cache on'
end
+ def test_exceptional_middleware_assigns_original_connection_id_on_error
+ connection_id = ActiveRecord::Base.connection_id
+
+ mw = ActiveRecord::QueryCache.new lambda { |env|
+ ActiveRecord::Base.connection_id = self.object_id
+ raise "lol borked"
+ }
+ assert_raises(RuntimeError) { mw.call({}) }
+
+ assert_equal connection_id, ActiveRecord::Base.connection_id
+ end
+
def test_middleware_delegates
called = false
mw = ActiveRecord::QueryCache.new lambda { |env|
@@ -151,16 +163,11 @@ class QueryCacheTest < ActiveRecord::TestCase
end
def test_cache_does_not_wrap_string_results_in_arrays
- if current_adapter?(:SQLite3Adapter)
- require 'sqlite3/version'
- sqlite3_version = RUBY_PLATFORM =~ /java/ ? Jdbc::SQLite3::VERSION : SQLite3::VERSION
- end
-
Task.cache do
# 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 > '1.2.5' || current_adapter?(:Mysql2Adapter) || current_adapter?(:MysqlAdapter)
+ elsif current_adapter?(:SQLite3Adapter) || current_adapter?(:Mysql2Adapter)
# Future versions of the sqlite3 adapter will return numeric
assert_instance_of Fixnum,
Task.connection.select_value("SELECT count(*) AS count_all FROM tasks")
@@ -169,6 +176,14 @@ class QueryCacheTest < ActiveRecord::TestCase
end
end
end
+
+ def test_cache_is_ignored_for_locked_relations
+ task = Task.find 1
+
+ Task.cache do
+ assert_queries(2) { task.lock!; task.lock! }
+ end
+ end
end
class QueryCacheExpiryTest < ActiveRecord::TestCase
diff --git a/activerecord/test/cases/quoting_test.rb b/activerecord/test/cases/quoting_test.rb
index 80ee74e41e..3dd11ae89d 100644
--- a/activerecord/test/cases/quoting_test.rb
+++ b/activerecord/test/cases/quoting_test.rb
@@ -216,6 +216,14 @@ module ActiveRecord
def test_string_with_crazy_column
assert_equal "'lo\\\\l'", @quoter.quote('lo\l', FakeColumn.new(:foo))
end
+
+ def test_quote_duration
+ assert_equal "1800", @quoter.quote(30.minutes)
+ end
+
+ def test_quote_duration_int_column
+ assert_equal "7200", @quoter.quote(2.hours, FakeColumn.new(:integer))
+ end
end
end
end
diff --git a/activerecord/test/cases/readonly_test.rb b/activerecord/test/cases/readonly_test.rb
index df0399f548..df076c97b4 100644
--- a/activerecord/test/cases/readonly_test.rb
+++ b/activerecord/test/cases/readonly_test.rb
@@ -49,7 +49,7 @@ class ReadOnlyTest < ActiveRecord::TestCase
post = Post.find(1)
assert !post.comments.empty?
assert !post.comments.any?(&:readonly?)
- assert !post.comments.all.any?(&:readonly?)
+ assert !post.comments.to_a.any?(&:readonly?)
assert post.comments.readonly(true).all?(&:readonly?)
end
@@ -71,13 +71,13 @@ class ReadOnlyTest < ActiveRecord::TestCase
end
def test_readonly_scoping
- Post.where('1=1').scoped do
+ Post.where('1=1').scoping do
assert !Post.find(1).readonly?
assert Post.readonly(true).find(1).readonly?
assert !Post.readonly(false).find(1).readonly?
end
- Post.joins(' ').scoped do
+ Post.joins(' ').scoping do
assert !Post.find(1).readonly?
assert Post.readonly.find(1).readonly?
assert !Post.readonly(false).find(1).readonly?
@@ -86,14 +86,14 @@ class ReadOnlyTest < ActiveRecord::TestCase
# Oracle barfs on this because the join includes unqualified and
# conflicting column names
unless current_adapter?(:OracleAdapter)
- Post.joins(', developers').scoped do
+ Post.joins(', developers').scoping do
assert Post.find(1).readonly?
assert Post.readonly.find(1).readonly?
assert !Post.readonly(false).find(1).readonly?
end
end
- Post.readonly(true).scoped do
+ Post.readonly(true).scoping do
assert Post.find(1).readonly?
assert Post.readonly.find(1).readonly?
assert !Post.readonly(false).find(1).readonly?
diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb
index 7dd5698dcf..588da68ec1 100644
--- a/activerecord/test/cases/reflection_test.rb
+++ b/activerecord/test/cases/reflection_test.rb
@@ -77,7 +77,7 @@ class ReflectionTest < ActiveRecord::TestCase
end
def test_reflection_klass_for_nested_class_name
- reflection = MacroReflection.new(:company, nil, { :class_name => 'MyApplication::Business::Company' }, ActiveRecord::Base)
+ reflection = MacroReflection.new(:company, nil, nil, { :class_name => 'MyApplication::Business::Company' }, ActiveRecord::Base)
assert_nothing_raised do
assert_equal MyApplication::Business::Company, reflection.klass
end
@@ -85,15 +85,15 @@ class ReflectionTest < ActiveRecord::TestCase
def test_aggregation_reflection
reflection_for_address = AggregateReflection.new(
- :composed_of, :address, { :mapping => [ %w(address_street street), %w(address_city city), %w(address_country country) ] }, Customer
+ :composed_of, :address, nil, { :mapping => [ %w(address_street street), %w(address_city city), %w(address_country country) ] }, Customer
)
reflection_for_balance = AggregateReflection.new(
- :composed_of, :balance, { :class_name => "Money", :mapping => %w(balance amount) }, Customer
+ :composed_of, :balance, nil, { :class_name => "Money", :mapping => %w(balance amount) }, Customer
)
reflection_for_gps_location = AggregateReflection.new(
- :composed_of, :gps_location, { }, Customer
+ :composed_of, :gps_location, nil, { }, Customer
)
assert Customer.reflect_on_all_aggregations.include?(reflection_for_gps_location)
@@ -117,7 +117,7 @@ class ReflectionTest < ActiveRecord::TestCase
end
def test_has_many_reflection
- reflection_for_clients = AssociationReflection.new(:has_many, :clients, { :order => "id", :dependent => :destroy }, Firm)
+ reflection_for_clients = AssociationReflection.new(:has_many, :clients, nil, { :order => "id", :dependent => :destroy }, Firm)
assert_equal reflection_for_clients, Firm.reflect_on_association(:clients)
@@ -129,7 +129,7 @@ class ReflectionTest < ActiveRecord::TestCase
end
def test_has_one_reflection
- reflection_for_account = AssociationReflection.new(:has_one, :account, { :foreign_key => "firm_id", :dependent => :destroy }, Firm)
+ reflection_for_account = AssociationReflection.new(:has_one, :account, nil, { :foreign_key => "firm_id", :dependent => :destroy }, Firm)
assert_equal reflection_for_account, Firm.reflect_on_association(:account)
assert_equal Account, Firm.reflect_on_association(:account).klass
@@ -214,21 +214,25 @@ class ReflectionTest < ActiveRecord::TestCase
assert_equal expected, actual
end
- def test_conditions
+ def test_scope_chain
expected = [
- [{ :tags => { :name => 'Blue' } }],
- [{ :taggings => { :comment => 'first' } }],
- [{ :posts => { :title => ['misc post by bob', 'misc post by mary'] } }]
+ [Tagging.reflect_on_association(:tag).scope, Post.reflect_on_association(:first_blue_tags).scope],
+ [Post.reflect_on_association(:first_taggings).scope],
+ [Author.reflect_on_association(:misc_posts).scope]
]
- actual = Author.reflect_on_association(:misc_post_first_blue_tags).conditions
+ actual = Author.reflect_on_association(:misc_post_first_blue_tags).scope_chain
assert_equal expected, actual
expected = [
- [{ :tags => { :name => 'Blue' } }, { :taggings => { :comment => 'first' } }, { :posts => { :title => ['misc post by bob', 'misc post by mary'] } }],
+ [
+ Tagging.reflect_on_association(:blue_tag).scope,
+ Post.reflect_on_association(:first_blue_tags_2).scope,
+ Author.reflect_on_association(:misc_post_first_blue_tags_2).scope
+ ],
[],
[]
]
- actual = Author.reflect_on_association(:misc_post_first_blue_tags_2).conditions
+ actual = Author.reflect_on_association(:misc_post_first_blue_tags_2).scope_chain
assert_equal expected, actual
end
@@ -254,10 +258,10 @@ class ReflectionTest < ActiveRecord::TestCase
end
def test_association_primary_key_raises_when_missing_primary_key
- reflection = ActiveRecord::Reflection::AssociationReflection.new(:fuu, :edge, {}, Author)
+ reflection = ActiveRecord::Reflection::AssociationReflection.new(:fuu, :edge, nil, {}, Author)
assert_raises(ActiveRecord::UnknownPrimaryKey) { reflection.association_primary_key }
- through = ActiveRecord::Reflection::ThroughReflection.new(:fuu, :edge, {}, Author)
+ through = ActiveRecord::Reflection::ThroughReflection.new(:fuu, :edge, nil, {}, Author)
through.stubs(:source_reflection).returns(stub_everything(:options => {}, :class_name => 'Edge'))
assert_raises(ActiveRecord::UnknownPrimaryKey) { through.association_primary_key }
end
@@ -268,7 +272,7 @@ class ReflectionTest < ActiveRecord::TestCase
end
def test_active_record_primary_key_raises_when_missing_primary_key
- reflection = ActiveRecord::Reflection::AssociationReflection.new(:fuu, :author, {}, Edge)
+ reflection = ActiveRecord::Reflection::AssociationReflection.new(:fuu, :author, nil, {}, Edge)
assert_raises(ActiveRecord::UnknownPrimaryKey) { reflection.active_record_primary_key }
end
@@ -286,32 +290,32 @@ class ReflectionTest < ActiveRecord::TestCase
end
def test_default_association_validation
- assert AssociationReflection.new(:has_many, :clients, {}, Firm).validate?
+ assert AssociationReflection.new(:has_many, :clients, nil, {}, Firm).validate?
- assert !AssociationReflection.new(:has_one, :client, {}, Firm).validate?
- assert !AssociationReflection.new(:belongs_to, :client, {}, Firm).validate?
- assert !AssociationReflection.new(:has_and_belongs_to_many, :clients, {}, Firm).validate?
+ assert !AssociationReflection.new(:has_one, :client, nil, {}, Firm).validate?
+ assert !AssociationReflection.new(:belongs_to, :client, nil, {}, Firm).validate?
+ assert !AssociationReflection.new(:has_and_belongs_to_many, :clients, nil, {}, Firm).validate?
end
def test_always_validate_association_if_explicit
- assert AssociationReflection.new(:has_one, :client, { :validate => true }, Firm).validate?
- assert AssociationReflection.new(:belongs_to, :client, { :validate => true }, Firm).validate?
- assert AssociationReflection.new(:has_many, :clients, { :validate => true }, Firm).validate?
- assert AssociationReflection.new(:has_and_belongs_to_many, :clients, { :validate => true }, Firm).validate?
+ assert AssociationReflection.new(:has_one, :client, nil, { :validate => true }, Firm).validate?
+ assert AssociationReflection.new(:belongs_to, :client, nil, { :validate => true }, Firm).validate?
+ assert AssociationReflection.new(:has_many, :clients, nil, { :validate => true }, Firm).validate?
+ assert AssociationReflection.new(:has_and_belongs_to_many, :clients, nil, { :validate => true }, Firm).validate?
end
def test_validate_association_if_autosave
- assert AssociationReflection.new(:has_one, :client, { :autosave => true }, Firm).validate?
- assert AssociationReflection.new(:belongs_to, :client, { :autosave => true }, Firm).validate?
- assert AssociationReflection.new(:has_many, :clients, { :autosave => true }, Firm).validate?
- assert AssociationReflection.new(:has_and_belongs_to_many, :clients, { :autosave => true }, Firm).validate?
+ assert AssociationReflection.new(:has_one, :client, nil, { :autosave => true }, Firm).validate?
+ assert AssociationReflection.new(:belongs_to, :client, nil, { :autosave => true }, Firm).validate?
+ assert AssociationReflection.new(:has_many, :clients, nil, { :autosave => true }, Firm).validate?
+ assert AssociationReflection.new(:has_and_belongs_to_many, :clients, nil, { :autosave => true }, Firm).validate?
end
def test_never_validate_association_if_explicit
- assert !AssociationReflection.new(:has_one, :client, { :autosave => true, :validate => false }, Firm).validate?
- assert !AssociationReflection.new(:belongs_to, :client, { :autosave => true, :validate => false }, Firm).validate?
- assert !AssociationReflection.new(:has_many, :clients, { :autosave => true, :validate => false }, Firm).validate?
- assert !AssociationReflection.new(:has_and_belongs_to_many, :clients, { :autosave => true, :validate => false }, Firm).validate?
+ assert !AssociationReflection.new(:has_one, :client, nil, { :autosave => true, :validate => false }, Firm).validate?
+ assert !AssociationReflection.new(:belongs_to, :client, nil, { :autosave => true, :validate => false }, Firm).validate?
+ assert !AssociationReflection.new(:has_many, :clients, nil, { :autosave => true, :validate => false }, Firm).validate?
+ assert !AssociationReflection.new(:has_and_belongs_to_many, :clients, nil, { :autosave => true, :validate => false }, Firm).validate?
end
def test_foreign_key
@@ -319,16 +323,68 @@ class ReflectionTest < ActiveRecord::TestCase
assert_equal "category_id", Post.reflect_on_association(:categorizations).foreign_key.to_s
end
- def test_through_reflection_conditions_do_not_modify_other_reflections
- orig_conds = Post.reflect_on_association(:first_blue_tags_2).conditions.inspect
- Author.reflect_on_association(:misc_post_first_blue_tags_2).conditions
- assert_equal orig_conds, Post.reflect_on_association(:first_blue_tags_2).conditions.inspect
+ def test_through_reflection_scope_chain_does_not_modify_other_reflections
+ orig_conds = Post.reflect_on_association(:first_blue_tags_2).scope_chain.inspect
+ Author.reflect_on_association(:misc_post_first_blue_tags_2).scope_chain
+ assert_equal orig_conds, Post.reflect_on_association(:first_blue_tags_2).scope_chain.inspect
end
def test_symbol_for_class_name
assert_equal Client, Firm.reflect_on_association(:unsorted_clients_with_symbol).klass
end
+ def test_join_table
+ category = Struct.new(:table_name, :pluralize_table_names).new('categories', true)
+ product = Struct.new(:table_name, :pluralize_table_names).new('products', true)
+
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :categories, nil, {}, product)
+ reflection.stubs(:klass).returns(category)
+ assert_equal 'categories_products', reflection.join_table
+
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :products, nil, {}, category)
+ reflection.stubs(:klass).returns(product)
+ assert_equal 'categories_products', reflection.join_table
+ end
+
+ def test_join_table_with_common_prefix
+ category = Struct.new(:table_name, :pluralize_table_names).new('catalog_categories', true)
+ product = Struct.new(:table_name, :pluralize_table_names).new('catalog_products', true)
+
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :categories, nil, {}, product)
+ reflection.stubs(:klass).returns(category)
+ assert_equal 'catalog_categories_products', reflection.join_table
+
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :products, nil, {}, category)
+ reflection.stubs(:klass).returns(product)
+ assert_equal 'catalog_categories_products', reflection.join_table
+ end
+
+ def test_join_table_with_different_prefix
+ category = Struct.new(:table_name, :pluralize_table_names).new('catalog_categories', true)
+ page = Struct.new(:table_name, :pluralize_table_names).new('content_pages', true)
+
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :categories, nil, {}, page)
+ reflection.stubs(:klass).returns(category)
+ assert_equal 'catalog_categories_content_pages', reflection.join_table
+
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :pages, nil, {}, category)
+ reflection.stubs(:klass).returns(page)
+ assert_equal 'catalog_categories_content_pages', reflection.join_table
+ end
+
+ def test_join_table_can_be_overridden
+ category = Struct.new(:table_name, :pluralize_table_names).new('categories', true)
+ product = Struct.new(:table_name, :pluralize_table_names).new('products', true)
+
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :categories, nil, { :join_table => 'product_categories' }, product)
+ reflection.stubs(:klass).returns(category)
+ assert_equal 'product_categories', reflection.join_table
+
+ reflection = AssociationReflection.new(:has_and_belongs_to_many, :products, nil, { :join_table => 'product_categories' }, category)
+ reflection.stubs(:klass).returns(product)
+ assert_equal 'product_categories', reflection.join_table
+ end
+
private
def assert_reflection(klass, association, options)
assert reflection = klass.reflect_on_association(association)
diff --git a/activerecord/test/cases/relation_scoping_test.rb b/activerecord/test/cases/relation_scoping_test.rb
index cf367242f2..d318dab1e1 100644
--- a/activerecord/test/cases/relation_scoping_test.rb
+++ b/activerecord/test/cases/relation_scoping_test.rb
@@ -106,7 +106,7 @@ class RelationScopingTest < ActiveRecord::TestCase
def test_scoped_find_include
# with the include, will retrieve only developers for the given project
scoped_developers = Developer.includes(:projects).scoping do
- Developer.where('projects.id' => 2).all
+ Developer.where('projects.id' => 2).to_a
end
assert scoped_developers.include?(developers(:david))
assert !scoped_developers.include?(developers(:jamis))
@@ -115,7 +115,7 @@ class RelationScopingTest < ActiveRecord::TestCase
def test_scoped_find_joins
scoped_developers = Developer.joins('JOIN developers_projects ON id = developer_id').scoping do
- Developer.where('developers_projects.project_id = 2').all
+ Developer.where('developers_projects.project_id = 2').to_a
end
assert scoped_developers.include?(developers(:david))
@@ -159,7 +159,7 @@ class RelationScopingTest < ActiveRecord::TestCase
rescue
end
- assert !Developer.scoped.where_values.include?("name = 'Jamis'")
+ assert !Developer.all.where_values.include?("name = 'Jamis'")
end
end
@@ -169,7 +169,7 @@ class NestedRelationScopingTest < ActiveRecord::TestCase
def test_merge_options
Developer.where('salary = 80000').scoping do
Developer.limit(10).scoping do
- devs = Developer.scoped
+ devs = Developer.all
assert_match '(salary = 80000)', devs.to_sql
assert_equal 10, devs.taken
end
@@ -312,7 +312,7 @@ class DefaultScopingTest < ActiveRecord::TestCase
fixtures :developers, :posts
def test_default_scope
- expected = Developer.scoped(:order => 'salary DESC').all.collect { |dev| dev.salary }
+ expected = Developer.all.merge!(:order => 'salary DESC').to_a.collect { |dev| dev.salary }
received = DeveloperOrderedBySalary.all.collect { |dev| dev.salary }
assert_equal expected, received
end
@@ -362,31 +362,31 @@ class DefaultScopingTest < ActiveRecord::TestCase
def test_default_scoping_with_threads
2.times do
- Thread.new { assert DeveloperOrderedBySalary.scoped.to_sql.include?('salary DESC') }.join
+ Thread.new { assert DeveloperOrderedBySalary.all.to_sql.include?('salary DESC') }.join
end
end
def test_default_scope_with_inheritance
- wheres = InheritedPoorDeveloperCalledJamis.scoped.where_values_hash
+ wheres = InheritedPoorDeveloperCalledJamis.all.where_values_hash
assert_equal "Jamis", wheres[:name]
assert_equal 50000, wheres[:salary]
end
def test_default_scope_with_module_includes
- wheres = ModuleIncludedPoorDeveloperCalledJamis.scoped.where_values_hash
+ wheres = ModuleIncludedPoorDeveloperCalledJamis.all.where_values_hash
assert_equal "Jamis", wheres[:name]
assert_equal 50000, wheres[:salary]
end
def test_default_scope_with_multiple_calls
- wheres = MultiplePoorDeveloperCalledJamis.scoped.where_values_hash
+ wheres = MultiplePoorDeveloperCalledJamis.all.where_values_hash
assert_equal "Jamis", wheres[:name]
assert_equal 50000, wheres[:salary]
end
def test_scope_overwrites_default
- expected = Developer.scoped(:order => 'salary DESC, name DESC').all.collect { |dev| dev.name }
- received = DeveloperOrderedBySalary.by_name.all.collect { |dev| dev.name }
+ expected = Developer.all.merge!(:order => ' name DESC, salary DESC').to_a.collect { |dev| dev.name }
+ received = DeveloperOrderedBySalary.by_name.to_a.collect { |dev| dev.name }
assert_equal expected, received
end
@@ -397,14 +397,14 @@ class DefaultScopingTest < ActiveRecord::TestCase
end
def test_order_after_reorder_combines_orders
- expected = Developer.order('name DESC, id DESC').collect { |dev| [dev.name, dev.id] }
+ expected = Developer.order('id DESC, name DESC').collect { |dev| [dev.name, dev.id] }
received = Developer.order('name ASC').reorder('name DESC').order('id DESC').collect { |dev| [dev.name, dev.id] }
assert_equal expected, received
end
- def test_order_in_default_scope_should_prevail
- expected = Developer.scoped(:order => 'salary desc').all.collect { |dev| dev.salary }
- received = DeveloperOrderedBySalary.scoped(:order => 'salary').all.collect { |dev| dev.salary }
+ def test_order_in_default_scope_should_not_prevail
+ expected = Developer.all.merge!(:order => 'salary').to_a.collect { |dev| dev.salary }
+ received = DeveloperOrderedBySalary.all.merge!(:order => 'salary').to_a.collect { |dev| dev.salary }
assert_equal expected, received
end
@@ -472,7 +472,7 @@ class DefaultScopingTest < ActiveRecord::TestCase
end
def test_default_scope_select_ignored_by_aggregations
- assert_equal DeveloperWithSelect.all.count, DeveloperWithSelect.count
+ assert_equal DeveloperWithSelect.all.to_a.count, DeveloperWithSelect.count
end
def test_default_scope_select_ignored_by_grouped_aggregations
@@ -508,10 +508,10 @@ class DefaultScopingTest < ActiveRecord::TestCase
threads << Thread.new do
Thread.current[:long_default_scope] = true
- assert_equal 1, ThreadsafeDeveloper.all.count
+ assert_equal 1, ThreadsafeDeveloper.all.to_a.count
end
threads << Thread.new do
- assert_equal 1, ThreadsafeDeveloper.all.count
+ assert_equal 1, ThreadsafeDeveloper.all.to_a.count
end
threads.each(&:join)
end
diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb
index b7486196c5..6399111be6 100644
--- a/activerecord/test/cases/relation_test.rb
+++ b/activerecord/test/cases/relation_test.rb
@@ -196,11 +196,14 @@ module ActiveRecord
end
test 'extending!' do
- mod = Module.new
+ mod, mod2 = Module.new, Module.new
assert relation.extending!(mod).equal?(relation)
- assert [mod], relation.extending_values
+ assert_equal [mod], relation.extending_values
assert relation.is_a?(mod)
+
+ relation.extending!(mod2)
+ assert_equal [mod, mod2], relation.extending_values
end
test 'extending! with empty args' do
@@ -249,5 +252,9 @@ module ActiveRecord
assert relation.merge!(where: :foo).equal?(relation)
assert_equal [:foo], relation.where_values
end
+
+ test 'merge with a proc' do
+ assert_equal [:foo], relation.merge(-> { where(:foo) }).where_values
+ end
end
end
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index 90367df5ee..684538940a 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -34,7 +34,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_bind_values
- relation = Post.scoped
+ relation = Post.all
assert_equal [], relation.bind_values
relation2 = relation.bind 'foo'
@@ -59,44 +59,44 @@ class RelationTest < ActiveRecord::TestCase
end
def test_scoped
- topics = Topic.scoped
+ topics = Topic.all
assert_kind_of ActiveRecord::Relation, topics
assert_equal 4, topics.size
end
def test_to_json
- assert_nothing_raised { Bird.scoped.to_json }
- assert_nothing_raised { Bird.scoped.all.to_json }
+ assert_nothing_raised { Bird.all.to_json }
+ assert_nothing_raised { Bird.all.to_a.to_json }
end
def test_to_yaml
- assert_nothing_raised { Bird.scoped.to_yaml }
- assert_nothing_raised { Bird.scoped.all.to_yaml }
+ assert_nothing_raised { Bird.all.to_yaml }
+ assert_nothing_raised { Bird.all.to_a.to_yaml }
end
def test_to_xml
- assert_nothing_raised { Bird.scoped.to_xml }
- assert_nothing_raised { Bird.scoped.all.to_xml }
+ assert_nothing_raised { Bird.all.to_xml }
+ assert_nothing_raised { Bird.all.to_a.to_xml }
end
def test_scoped_all
- topics = Topic.scoped.all
+ topics = Topic.all.to_a
assert_kind_of Array, topics
assert_no_queries { assert_equal 4, topics.size }
end
def test_loaded_all
- topics = Topic.scoped
+ topics = Topic.all
assert_queries(1) do
- 2.times { assert_equal 4, topics.all.size }
+ 2.times { assert_equal 4, topics.to_a.size }
end
assert topics.loaded?
end
def test_scoped_first
- topics = Topic.scoped.order('id ASC')
+ topics = Topic.all.order('id ASC')
assert_queries(1) do
2.times { assert_equal "The First Topic", topics.first.title }
@@ -106,10 +106,10 @@ class RelationTest < ActiveRecord::TestCase
end
def test_loaded_first
- topics = Topic.scoped.order('id ASC')
+ topics = Topic.all.order('id ASC')
assert_queries(1) do
- topics.all # force load
+ topics.to_a # force load
2.times { assert_equal "The First Topic", topics.first.title }
end
@@ -117,7 +117,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_reload
- topics = Topic.scoped
+ topics = Topic.all
assert_queries(1) do
2.times { topics.to_a }
@@ -165,13 +165,13 @@ class RelationTest < ActiveRecord::TestCase
end
def test_finding_with_order_concatenated
- topics = Topic.order('author_name').order('title')
+ topics = Topic.order('title').order('author_name')
assert_equal 4, topics.to_a.size
assert_equal topics(:fourth).title, topics.first.title
end
def test_finding_with_reorder
- topics = Topic.order('author_name').order('title').reorder('id').all
+ topics = Topic.order('author_name').order('title').reorder('id').to_a
topics_titles = topics.map{ |t| t.title }
assert_equal ['The First Topic', 'The Second Topic of the day', 'The Third Topic of the day', 'The Fourth Topic of the day'], topics_titles
end
@@ -218,14 +218,14 @@ class RelationTest < ActiveRecord::TestCase
end
def test_select_with_block
- even_ids = Developer.scoped.select {|d| d.id % 2 == 0 }.map(&:id)
+ even_ids = Developer.all.select {|d| d.id % 2 == 0 }.map(&:id)
assert_equal [2, 4, 6, 8, 10], even_ids.sort
end
def test_none
assert_no_queries do
assert_equal [], Developer.none
- assert_equal [], Developer.scoped.none
+ assert_equal [], Developer.all.none
end
end
@@ -294,7 +294,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_find_on_hash_conditions
- assert_equal Topic.scoped(:where => {:approved => false}).all, Topic.where({ :approved => false }).to_a
+ assert_equal Topic.all.merge!(:where => {:approved => false}).to_a, Topic.where({ :approved => false }).to_a
end
def test_joins_with_string_array
@@ -307,15 +307,15 @@ class RelationTest < ActiveRecord::TestCase
end
def test_scoped_responds_to_delegated_methods
- relation = Topic.scoped
+ relation = Topic.all
["map", "uniq", "sort", "insert", "delete", "update"].each do |method|
- assert_respond_to relation, method, "Topic.scoped should respond to #{method.inspect}"
+ assert_respond_to relation, method, "Topic.all should respond to #{method.inspect}"
end
end
def test_respond_to_delegates_to_relation
- relation = Topic.scoped
+ relation = Topic.all
fake_arel = Struct.new(:responds) {
def respond_to? method, access = false
responds << [method, access]
@@ -334,20 +334,20 @@ class RelationTest < ActiveRecord::TestCase
end
def test_respond_to_dynamic_finders
- relation = Topic.scoped
+ relation = Topic.all
["find_by_title", "find_by_title_and_author_name", "find_or_create_by_title", "find_or_initialize_by_title_and_author_name"].each do |method|
- assert_respond_to relation, method, "Topic.scoped should respond to #{method.inspect}"
+ assert_respond_to relation, method, "Topic.all should respond to #{method.inspect}"
end
end
def test_respond_to_class_methods_and_scopes
- assert Topic.scoped.respond_to?(:by_lifo)
+ assert Topic.all.respond_to?(:by_lifo)
end
def test_find_with_readonly_option
- Developer.scoped.each { |d| assert !d.readonly? }
- Developer.scoped.readonly.each { |d| assert d.readonly? }
+ Developer.all.each { |d| assert !d.readonly? }
+ Developer.all.readonly.each { |d| assert d.readonly? }
end
def test_eager_association_loading_of_stis_with_multiple_references
@@ -396,7 +396,7 @@ class RelationTest < ActiveRecord::TestCase
end
assert_queries(2) do
- posts = Post.scoped.includes(:comments).order('posts.id')
+ posts = Post.all.includes(:comments).order('posts.id')
assert posts.first.comments.first
end
@@ -413,12 +413,12 @@ class RelationTest < ActiveRecord::TestCase
end
def test_default_scope_with_conditions_string
- assert_equal Developer.where(name: 'David').map(&:id).sort, DeveloperCalledDavid.scoped.map(&:id).sort
+ assert_equal Developer.where(name: 'David').map(&:id).sort, DeveloperCalledDavid.all.map(&:id).sort
assert_nil DeveloperCalledDavid.create!.name
end
def test_default_scope_with_conditions_hash
- assert_equal Developer.where(name: 'Jamis').map(&:id).sort, DeveloperCalledJamis.scoped.map(&:id).sort
+ assert_equal Developer.where(name: 'Jamis').map(&:id).sort, DeveloperCalledJamis.all.map(&:id).sort
assert_equal 'Jamis', DeveloperCalledJamis.create!.name
end
@@ -457,20 +457,20 @@ class RelationTest < ActiveRecord::TestCase
assert_equal expected_taggings, author.taggings.uniq.sort_by { |t| t.id }
end
- authors = Author.scoped
+ authors = Author.all
assert_equal david, authors.find_by_id_and_name(david.id, david.name)
assert_equal david, authors.find_by_id_and_name!(david.id, david.name)
end
def test_dynamic_find_by_attributes_bang
- author = Author.scoped.find_by_id!(authors(:david).id)
+ author = Author.all.find_by_id!(authors(:david).id)
assert_equal "David", author.name
- assert_raises(ActiveRecord::RecordNotFound) { Author.scoped.find_by_id_and_name!(20, 'invalid') }
+ assert_raises(ActiveRecord::RecordNotFound) { Author.all.find_by_id_and_name!(20, 'invalid') }
end
def test_find_id
- authors = Author.scoped
+ authors = Author.all
david = authors.find(authors(:david).id)
assert_equal 'David', david.name
@@ -493,14 +493,14 @@ class RelationTest < ActiveRecord::TestCase
end
def test_find_in_empty_array
- authors = Author.scoped.where(:id => [])
- assert_blank authors.all
+ authors = Author.all.where(:id => [])
+ assert_blank authors.to_a
end
def test_where_with_ar_object
author = Author.first
- authors = Author.scoped.where(:id => author)
- assert_equal 1, authors.all.length
+ authors = Author.all.where(:id => author)
+ assert_equal 1, authors.to_a.length
end
def test_find_with_list_of_ar
@@ -528,7 +528,7 @@ class RelationTest < ActiveRecord::TestCase
relation = relation.where(:name => david.name)
relation = relation.where(:name => 'Santiago')
relation = relation.where(:id => david.id)
- assert_equal [], relation.all
+ assert_equal [], relation.to_a
end
def test_multi_where_ands_queries
@@ -547,7 +547,7 @@ class RelationTest < ActiveRecord::TestCase
].inject(Author.unscoped) do |memo, param|
memo.where(param)
end
- assert_equal [], relation.all
+ assert_equal [], relation.to_a
end
def test_find_all_using_where_with_relation
@@ -556,7 +556,7 @@ class RelationTest < ActiveRecord::TestCase
# assert_queries(2) {
assert_queries(1) {
relation = Author.where(:id => Author.where(:id => david.id))
- assert_equal [david], relation.all
+ assert_equal [david], relation.to_a
}
end
@@ -566,7 +566,7 @@ class RelationTest < ActiveRecord::TestCase
# assert_queries(2) {
assert_queries(1) {
relation = Minivan.where(:minivan_id => Minivan.where(:name => cool_first.name))
- assert_equal [cool_first], relation.all
+ assert_equal [cool_first], relation.to_a
}
end
@@ -577,7 +577,7 @@ class RelationTest < ActiveRecord::TestCase
assert_queries(1) {
relation = Author.where(:id => subquery)
- assert_equal [david], relation.all
+ assert_equal [david], relation.to_a
}
assert_equal 0, subquery.select_values.size
@@ -587,7 +587,7 @@ class RelationTest < ActiveRecord::TestCase
david = authors(:david)
assert_queries(1) {
relation = Author.where(:id => Author.joins(:posts).where(:id => david.id))
- assert_equal [david], relation.all
+ assert_equal [david], relation.to_a
}
end
@@ -596,7 +596,7 @@ class RelationTest < ActiveRecord::TestCase
david = authors(:david)
assert_queries(1) {
relation = Author.where(:name => Author.where(:id => david.id).select(:name))
- assert_equal [david], relation.all
+ assert_equal [david], relation.to_a
}
end
@@ -615,7 +615,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_last
- authors = Author.scoped
+ authors = Author.all
assert_equal authors(:bob), authors.last
end
@@ -668,10 +668,29 @@ class RelationTest < ActiveRecord::TestCase
assert_equal [developers(:poor_jamis)], dev_with_count.to_a
end
+ def test_relation_merging_with_arel_equalities_keeps_last_equality
+ devs = Developer.where(Developer.arel_table[:salary].eq(80000)).merge(
+ Developer.where(Developer.arel_table[:salary].eq(9000))
+ )
+ assert_equal [developers(:poor_jamis)], devs.to_a
+ end
+
+ def test_relation_merging_with_arel_equalities_keeps_last_equality_with_non_attribute_left_hand
+ salary_attr = Developer.arel_table[:salary]
+ devs = Developer.where(
+ Arel::Nodes::NamedFunction.new('abs', [salary_attr]).eq(80000)
+ ).merge(
+ Developer.where(
+ Arel::Nodes::NamedFunction.new('abs', [salary_attr]).eq(9000)
+ )
+ )
+ assert_equal [developers(:poor_jamis)], devs.to_a
+ end
+
def test_relation_merging_with_eager_load
relations = []
- 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 << Post.order('comments.id DESC').merge(Post.eager_load(:last_comment)).merge(Post.all)
+ relations << Post.eager_load(:last_comment).merge(Post.order('comments.id DESC')).merge(Post.all)
relations.each do |posts|
post = posts.find { |p| p.id == 1 }
@@ -685,7 +704,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_relation_merging_with_preload
- [Post.scoped.merge(Post.preload(:author)), Post.preload(:author).merge(Post.scoped)].each do |posts|
+ [Post.all.merge(Post.preload(:author)), Post.preload(:author).merge(Post.all)].each do |posts|
assert_queries(2) { assert posts.first.author }
end
end
@@ -695,8 +714,16 @@ class RelationTest < ActiveRecord::TestCase
assert_equal 1, comments.count
end
+ def test_relation_merging_with_association
+ assert_queries(2) do # one for loading post, and another one merged query
+ post = Post.where(:body => 'Such a lovely day').first
+ comments = Comment.where(:body => 'Thank you for the welcome').merge(post.comments)
+ assert_equal 1, comments.count
+ end
+ end
+
def test_count
- posts = Post.scoped
+ posts = Post.all
assert_equal 11, posts.count
assert_equal 11, posts.count(:all)
@@ -707,7 +734,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_count_with_distinct
- posts = Post.scoped
+ posts = Post.all
assert_equal 3, posts.count(:comments_count, :distinct => true)
assert_equal 11, posts.count(:comments_count, :distinct => false)
@@ -718,7 +745,7 @@ class RelationTest < ActiveRecord::TestCase
def test_count_explicit_columns
Post.update_all(:comments_count => nil)
- posts = Post.scoped
+ posts = Post.all
assert_equal [0], posts.select('comments_count').where('id is not null').group('id').order('id').count.values.uniq
assert_equal 0, posts.where('id is not null').select('comments_count').count
@@ -730,13 +757,13 @@ class RelationTest < ActiveRecord::TestCase
end
def test_multiple_selects
- post = Post.scoped.select('comments_count').select('title').order("id ASC").first
+ post = Post.all.select('comments_count').select('title').order("id ASC").first
assert_equal "Welcome to the weblog", post.title
assert_equal 2, post.comments_count
end
def test_size
- posts = Post.scoped
+ posts = Post.all
assert_queries(1) { assert_equal 11, posts.size }
assert ! posts.loaded?
@@ -782,7 +809,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_empty
- posts = Post.scoped
+ posts = Post.all
assert_queries(1) { assert_equal false, posts.empty? }
assert ! posts.loaded?
@@ -808,7 +835,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_any
- posts = Post.scoped
+ posts = Post.all
# 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
@@ -830,7 +857,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_many
- posts = Post.scoped
+ posts = Post.all
assert_queries(2) do
assert posts.many? # Uses COUNT()
@@ -842,14 +869,14 @@ class RelationTest < ActiveRecord::TestCase
end
def test_many_with_limits
- posts = Post.scoped
+ posts = Post.all
assert posts.many?
assert ! posts.limit(1).many?
end
def test_build
- posts = Post.scoped
+ posts = Post.all
post = posts.new
assert_kind_of Post, post
@@ -864,7 +891,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_create
- birds = Bird.scoped
+ birds = Bird.all
sparrow = birds.create
assert_kind_of Bird, sparrow
@@ -876,7 +903,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_create_bang
- birds = Bird.scoped
+ birds = Bird.all
assert_raises(ActiveRecord::RecordInvalid) { birds.create! }
@@ -1018,24 +1045,24 @@ class RelationTest < ActiveRecord::TestCase
def test_except
relation = Post.where(:author_id => 1).order('id ASC').limit(1)
- assert_equal [posts(:welcome)], relation.all
+ assert_equal [posts(:welcome)], relation.to_a
author_posts = relation.except(:order, :limit)
- assert_equal Post.where(:author_id => 1).all, author_posts.all
+ assert_equal Post.where(:author_id => 1).to_a, author_posts.to_a
all_posts = relation.except(:where, :order, :limit)
- assert_equal Post.all, all_posts.all
+ assert_equal Post.all, all_posts
end
def test_only
relation = Post.where(:author_id => 1).order('id ASC').limit(1)
- assert_equal [posts(:welcome)], relation.all
+ assert_equal [posts(:welcome)], relation.to_a
author_posts = relation.only(:where)
- assert_equal Post.where(:author_id => 1).all, author_posts.all
+ assert_equal Post.where(:author_id => 1).to_a, author_posts.to_a
all_posts = relation.only(:limit)
- assert_equal Post.limit(1).all.first, all_posts.first
+ assert_equal Post.limit(1).to_a.first, all_posts.first
end
def test_anonymous_extension
@@ -1056,24 +1083,24 @@ class RelationTest < ActiveRecord::TestCase
end
def test_order_by_relation_attribute
- assert_equal Post.order(Post.arel_table[:title]).all, Post.order("title").all
+ assert_equal Post.order(Post.arel_table[:title]).to_a, Post.order("title").to_a
end
def test_default_scope_order_with_scope_order
- assert_equal 'zyke', CoolCar.order_using_new_style.limit(1).first.name
- assert_equal 'zyke', FastCar.order_using_new_style.limit(1).first.name
+ assert_equal 'honda', CoolCar.order_using_new_style.limit(1).first.name
+ assert_equal 'honda', FastCar.order_using_new_style.limit(1).first.name
end
def test_order_using_scoping
car1 = CoolCar.order('id DESC').scoping do
- CoolCar.scoped(:order => 'id asc').first
+ CoolCar.all.merge!(:order => 'id asc').first
end
- assert_equal 'zyke', car1.name
+ assert_equal 'honda', car1.name
car2 = FastCar.order('id DESC').scoping do
- FastCar.scoped(:order => 'id asc').first
+ FastCar.all.merge!(:order => 'id asc').first
end
- assert_equal 'zyke', car2.name
+ assert_equal 'honda', car2.name
end
def test_unscoped_block_style
@@ -1090,7 +1117,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_primary_key
- assert_equal "id", Post.scoped.primary_key
+ assert_equal "id", Post.all.primary_key
end
def test_eager_loading_with_conditions_on_joins
@@ -1114,6 +1141,10 @@ class RelationTest < ActiveRecord::TestCase
assert_equal authors(:david), Author.order('id DESC , name DESC').last
end
+ def test_update_all_with_blank_argument
+ assert_raises(ArgumentError) { Comment.update_all({}) }
+ end
+
def test_update_all_with_joins
comments = Comment.joins(:post).where('posts.id' => posts(:welcome).id)
count = comments.count
@@ -1214,7 +1245,7 @@ class RelationTest < ActiveRecord::TestCase
end
def test_presence
- topics = Topic.scoped
+ topics = Topic.all
# the first query is triggered because there are no topics yet.
assert_queries(1) { assert topics.present? }
@@ -1248,7 +1279,7 @@ class RelationTest < ActiveRecord::TestCase
end
test "find_by returns nil if the record is missing" do
- assert_equal nil, Post.scoped.find_by("1 = 0")
+ assert_equal nil, Post.all.find_by("1 = 0")
end
test "find_by doesn't have implicit ordering" do
@@ -1273,7 +1304,73 @@ class RelationTest < ActiveRecord::TestCase
test "find_by! raises RecordNotFound if the record is missing" do
assert_raises(ActiveRecord::RecordNotFound) do
- Post.scoped.find_by!("1 = 0")
+ Post.all.find_by!("1 = 0")
+ end
+ end
+
+ test "loaded relations cannot be mutated by multi value methods" do
+ relation = Post.all
+ relation.to_a
+
+ assert_raises(ActiveRecord::ImmutableRelation) do
+ relation.where! 'foo'
+ end
+ end
+
+ test "loaded relations cannot be mutated by single value methods" do
+ relation = Post.all
+ relation.to_a
+
+ assert_raises(ActiveRecord::ImmutableRelation) do
+ relation.limit! 5
+ end
+ end
+
+ test "loaded relations cannot be mutated by merge!" do
+ relation = Post.all
+ relation.to_a
+
+ assert_raises(ActiveRecord::ImmutableRelation) do
+ relation.merge! where: 'foo'
+ end
+ end
+
+ test "relations show the records in #inspect" do
+ relation = Post.limit(2)
+ assert_equal "#<ActiveRecord::Relation [#{Post.limit(2).map(&:inspect).join(', ')}]>", relation.inspect
+ end
+
+ test "relations limit the records in #inspect at 10" do
+ relation = Post.limit(11)
+ assert_equal "#<ActiveRecord::Relation [#{Post.limit(10).map(&:inspect).join(', ')}, ...]>", relation.inspect
+ end
+
+ test "already-loaded relations don't perform a new query in #inspect" do
+ relation = Post.limit(2)
+ relation.to_a
+
+ expected = "#<ActiveRecord::Relation [#{Post.limit(2).map(&:inspect).join(', ')}]>"
+
+ assert_no_queries do
+ assert_equal expected, relation.inspect
+ end
+ end
+
+ test 'using a custom table affects the wheres' do
+ table_alias = Post.arel_table.alias('omg_posts')
+
+ relation = ActiveRecord::Relation.new Post, table_alias
+ relation.where!(:foo => "bar")
+
+ node = relation.arel.constraints.first.grep(Arel::Attributes::Attribute).first
+ assert_equal table_alias, node.relation
+ end
+
+ test '#load' do
+ relation = Post.all
+ assert_queries(1) do
+ assert_equal relation, relation.load
end
+ assert_no_queries { relation.to_a }
end
end
diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb
index ab80dd1d6d..01dd25a9df 100644
--- a/activerecord/test/cases/schema_dumper_test.rb
+++ b/activerecord/test/cases/schema_dumper_test.rb
@@ -257,6 +257,13 @@ class SchemaDumperTest < ActiveRecord::TestCase
end
end
+ def test_schema_dump_includes_uuid_shorthand_definition
+ output = standard_dump
+ if %r{create_table "poistgresql_uuids"} =~ output
+ assert_match %r{t.uuid "guid"}, output
+ end
+ end
+
def test_schema_dump_includes_hstores_shorthand_definition
output = standard_dump
if %r{create_table "postgresql_hstores"} =~ output
@@ -294,4 +301,36 @@ class SchemaDumperTest < ActiveRecord::TestCase
output = standard_dump
assert_match %r{create_table "subscribers", :id => false}, output
end
+
+ class CreateDogMigration < ActiveRecord::Migration
+ def up
+ create_table("dogs") do |t|
+ t.column :name, :string
+ end
+ add_index "dogs", [:name]
+ end
+ def down
+ drop_table("dogs")
+ end
+ end
+
+ def test_schema_dump_with_table_name_prefix_and_suffix
+ original, $stdout = $stdout, StringIO.new
+ ActiveRecord::Base.table_name_prefix = 'foo_'
+ ActiveRecord::Base.table_name_suffix = '_bar'
+
+ migration = CreateDogMigration.new
+ migration.migrate(:up)
+
+ output = standard_dump
+ assert_no_match %r{create_table "foo_.+_bar"}, output
+ assert_no_match %r{create_index "foo_.+_bar"}, output
+ assert_no_match %r{create_table "schema_migrations"}, output
+ ensure
+ migration.migrate(:down)
+
+ ActiveRecord::Base.table_name_suffix = ActiveRecord::Base.table_name_prefix = ''
+ $stdout = original
+ end
+
end
diff --git a/activerecord/test/cases/serialization_test.rb b/activerecord/test/cases/serialization_test.rb
index a4c065e667..10d8ccc711 100644
--- a/activerecord/test/cases/serialization_test.rb
+++ b/activerecord/test/cases/serialization_test.rb
@@ -51,4 +51,10 @@ class SerializationTest < ActiveRecord::TestCase
assert_equal @contact_attributes[:awesome], contact.awesome, "For #{format}"
end
end
+
+ def test_serialized_attributes_are_class_level_settings
+ topic = Topic.new
+ assert_raise(NoMethodError) { topic.serialized_attributes = [] }
+ assert_deprecated { topic.serialized_attributes }
+ end
end
diff --git a/activerecord/test/cases/session_store/sql_bypass_test.rb b/activerecord/test/cases/session_store/sql_bypass_test.rb
index 6749d4ce98..b8cf4cf2cc 100644
--- a/activerecord/test/cases/session_store/sql_bypass_test.rb
+++ b/activerecord/test/cases/session_store/sql_bypass_test.rb
@@ -56,6 +56,20 @@ module ActiveRecord
s.destroy
assert_nil SqlBypass.find_by_session_id session_id
end
+
+ def test_data_column
+ SqlBypass.drop_table! if exists = Session.table_exists?
+ old, SqlBypass.data_column = SqlBypass.data_column, 'foo'
+ SqlBypass.create_table!
+
+ session_id = 20
+ SqlBypass.new(:data => 'hello', :session_id => session_id).save
+ assert_equal 'hello', SqlBypass.find_by_session_id(session_id).data
+ ensure
+ SqlBypass.drop_table!
+ SqlBypass.data_column = old
+ SqlBypass.create_table! if exists
+ end
end
end
end
diff --git a/activerecord/test/cases/store_test.rb b/activerecord/test/cases/store_test.rb
index 79476ed2a4..fb0d116c08 100644
--- a/activerecord/test/cases/store_test.rb
+++ b/activerecord/test/cases/store_test.rb
@@ -13,7 +13,7 @@ class StoreTest < ActiveRecord::TestCase
assert_equal 'black', @john.color
assert_nil @john.homepage
end
-
+
test "writing store attributes through accessors" do
@john.color = 'red'
@john.homepage = '37signals.com'
@@ -34,6 +34,11 @@ class StoreTest < ActiveRecord::TestCase
assert @john.settings_changed?
end
+ test "updating the store won't mark it as changed if an attribute isn't changed" do
+ @john.color = @john.color
+ assert !@john.settings_changed?
+ end
+
test "object initialization with not nullable column" do
assert_equal true, @john.remember_login
end
@@ -111,4 +116,14 @@ class StoreTest < ActiveRecord::TestCase
@john.is_a_good_guy = false
assert_equal false, @john.is_a_good_guy
end
+
+ test "stored attributes are returned" do
+ assert_equal [:color, :homepage], Admin::User.stored_attributes[:settings]
+ end
+
+ test "stores_attributes are class level settings" do
+ assert_raise(NoMethodError) { @john.stored_attributes = Hash.new }
+ assert_raise(NoMethodError) { @john.stored_attributes }
+ end
+
end
diff --git a/activerecord/test/cases/tasks/database_tasks_test.rb b/activerecord/test/cases/tasks/database_tasks_test.rb
new file mode 100644
index 0000000000..4f3489b7a5
--- /dev/null
+++ b/activerecord/test/cases/tasks/database_tasks_test.rb
@@ -0,0 +1,302 @@
+require 'cases/helper'
+
+module ActiveRecord
+ module DatabaseTasksSetupper
+ def setup
+ @mysql_tasks, @postgresql_tasks, @sqlite_tasks = stub, stub, stub
+ ActiveRecord::Tasks::MySQLDatabaseTasks.stubs(:new).returns @mysql_tasks
+ ActiveRecord::Tasks::PostgreSQLDatabaseTasks.stubs(:new).returns @postgresql_tasks
+ ActiveRecord::Tasks::SQLiteDatabaseTasks.stubs(:new).returns @sqlite_tasks
+ end
+ end
+
+ ADAPTERS_TASKS = {
+ :mysql => :mysql_tasks,
+ :mysql2 => :mysql_tasks,
+ :postgresql => :postgresql_tasks,
+ :sqlite3 => :sqlite_tasks
+ }
+
+ class DatabaseTasksRegisterTask < ActiveRecord::TestCase
+ def test_register_task
+ klazz = Class.new do
+ def initialize(*arguments); end
+ def structure_dump(filename); end
+ end
+ instance = klazz.new
+
+ klazz.stubs(:new).returns instance
+ instance.expects(:structure_dump).with("awesome-file.sql")
+
+ ActiveRecord::Tasks::DatabaseTasks.register_task(/foo/, klazz)
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump({'adapter' => :foo}, "awesome-file.sql")
+ end
+ end
+
+ class DatabaseTasksCreateTest < ActiveRecord::TestCase
+ include DatabaseTasksSetupper
+
+ ADAPTERS_TASKS.each do |k, v|
+ define_method("test_#{k}_create") do
+ eval("@#{v}").expects(:create)
+ ActiveRecord::Tasks::DatabaseTasks.create 'adapter' => k
+ end
+ end
+ end
+
+ class DatabaseTasksCreateAllTest < ActiveRecord::TestCase
+ def setup
+ @configurations = {'development' => {'database' => 'my-db'}}
+
+ ActiveRecord::Base.stubs(:configurations).returns(@configurations)
+ end
+
+ def test_ignores_configurations_without_databases
+ @configurations['development'].merge!('database' => nil)
+
+ ActiveRecord::Tasks::DatabaseTasks.expects(:create).never
+
+ ActiveRecord::Tasks::DatabaseTasks.create_all
+ end
+
+ def test_ignores_remote_databases
+ @configurations['development'].merge!('host' => 'my.server.tld')
+ $stderr.stubs(:puts).returns(nil)
+
+ ActiveRecord::Tasks::DatabaseTasks.expects(:create).never
+
+ ActiveRecord::Tasks::DatabaseTasks.create_all
+ end
+
+ def test_warning_for_remote_databases
+ @configurations['development'].merge!('host' => 'my.server.tld')
+
+ $stderr.expects(:puts).with('This task only modifies local databases. my-db is on a remote host.')
+
+ ActiveRecord::Tasks::DatabaseTasks.create_all
+ end
+
+ def test_creates_configurations_with_local_ip
+ @configurations['development'].merge!('host' => '127.0.0.1')
+
+ ActiveRecord::Tasks::DatabaseTasks.expects(:create)
+
+ ActiveRecord::Tasks::DatabaseTasks.create_all
+ end
+
+ def test_creates_configurations_with_local_host
+ @configurations['development'].merge!('host' => 'localhost')
+
+ ActiveRecord::Tasks::DatabaseTasks.expects(:create)
+
+ ActiveRecord::Tasks::DatabaseTasks.create_all
+ end
+
+ def test_creates_configurations_with_blank_hosts
+ @configurations['development'].merge!('host' => nil)
+
+ ActiveRecord::Tasks::DatabaseTasks.expects(:create)
+
+ ActiveRecord::Tasks::DatabaseTasks.create_all
+ end
+ end
+
+ class DatabaseTasksCreateCurrentTest < ActiveRecord::TestCase
+ def setup
+ @configurations = {
+ 'development' => {'database' => 'dev-db'},
+ 'test' => {'database' => 'test-db'},
+ 'production' => {'database' => 'prod-db'}
+ }
+
+ ActiveRecord::Base.stubs(:configurations).returns(@configurations)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_creates_current_environment_database
+ ActiveRecord::Tasks::DatabaseTasks.expects(:create).
+ with('database' => 'prod-db')
+
+ ActiveRecord::Tasks::DatabaseTasks.create_current(
+ ActiveSupport::StringInquirer.new('production')
+ )
+ end
+
+ def test_creates_test_database_when_environment_is_database
+ ActiveRecord::Tasks::DatabaseTasks.expects(:create).
+ with('database' => 'dev-db')
+ ActiveRecord::Tasks::DatabaseTasks.expects(:create).
+ with('database' => 'test-db')
+
+ ActiveRecord::Tasks::DatabaseTasks.create_current(
+ ActiveSupport::StringInquirer.new('development')
+ )
+ end
+
+ def test_establishes_connection_for_the_given_environment
+ ActiveRecord::Tasks::DatabaseTasks.stubs(:create).returns true
+
+ ActiveRecord::Base.expects(:establish_connection).with('development')
+
+ ActiveRecord::Tasks::DatabaseTasks.create_current(
+ ActiveSupport::StringInquirer.new('development')
+ )
+ end
+ end
+
+ class DatabaseTasksDropTest < ActiveRecord::TestCase
+ include DatabaseTasksSetupper
+
+ ADAPTERS_TASKS.each do |k, v|
+ define_method("test_#{k}_drop") do
+ eval("@#{v}").expects(:drop)
+ ActiveRecord::Tasks::DatabaseTasks.drop 'adapter' => k
+ end
+ end
+ end
+
+ class DatabaseTasksDropAllTest < ActiveRecord::TestCase
+ def setup
+ @configurations = {:development => {'database' => 'my-db'}}
+
+ ActiveRecord::Base.stubs(:configurations).returns(@configurations)
+ end
+
+ def test_ignores_configurations_without_databases
+ @configurations[:development].merge!('database' => nil)
+
+ ActiveRecord::Tasks::DatabaseTasks.expects(:drop).never
+
+ ActiveRecord::Tasks::DatabaseTasks.drop_all
+ end
+
+ def test_ignores_remote_databases
+ @configurations[:development].merge!('host' => 'my.server.tld')
+ $stderr.stubs(:puts).returns(nil)
+
+ ActiveRecord::Tasks::DatabaseTasks.expects(:drop).never
+
+ ActiveRecord::Tasks::DatabaseTasks.drop_all
+ end
+
+ def test_warning_for_remote_databases
+ @configurations[:development].merge!('host' => 'my.server.tld')
+
+ $stderr.expects(:puts).with('This task only modifies local databases. my-db is on a remote host.')
+
+ ActiveRecord::Tasks::DatabaseTasks.drop_all
+ end
+
+ def test_creates_configurations_with_local_ip
+ @configurations[:development].merge!('host' => '127.0.0.1')
+
+ ActiveRecord::Tasks::DatabaseTasks.expects(:drop)
+
+ ActiveRecord::Tasks::DatabaseTasks.drop_all
+ end
+
+ def test_creates_configurations_with_local_host
+ @configurations[:development].merge!('host' => 'localhost')
+
+ ActiveRecord::Tasks::DatabaseTasks.expects(:drop)
+
+ ActiveRecord::Tasks::DatabaseTasks.drop_all
+ end
+
+ def test_creates_configurations_with_blank_hosts
+ @configurations[:development].merge!('host' => nil)
+
+ ActiveRecord::Tasks::DatabaseTasks.expects(:drop)
+
+ ActiveRecord::Tasks::DatabaseTasks.drop_all
+ end
+ end
+
+ class DatabaseTasksDropCurrentTest < ActiveRecord::TestCase
+ def setup
+ @configurations = {
+ 'development' => {'database' => 'dev-db'},
+ 'test' => {'database' => 'test-db'},
+ 'production' => {'database' => 'prod-db'}
+ }
+
+ ActiveRecord::Base.stubs(:configurations).returns(@configurations)
+ end
+
+ def test_creates_current_environment_database
+ ActiveRecord::Tasks::DatabaseTasks.expects(:drop).
+ with('database' => 'prod-db')
+
+ ActiveRecord::Tasks::DatabaseTasks.drop_current(
+ ActiveSupport::StringInquirer.new('production')
+ )
+ end
+
+ def test_creates_test_database_when_environment_is_database
+ ActiveRecord::Tasks::DatabaseTasks.expects(:drop).
+ with('database' => 'dev-db')
+ ActiveRecord::Tasks::DatabaseTasks.expects(:drop).
+ with('database' => 'test-db')
+
+ ActiveRecord::Tasks::DatabaseTasks.drop_current(
+ ActiveSupport::StringInquirer.new('development')
+ )
+ end
+ end
+
+
+ class DatabaseTasksPurgeTest < ActiveRecord::TestCase
+ include DatabaseTasksSetupper
+
+ ADAPTERS_TASKS.each do |k, v|
+ define_method("test_#{k}_purge") do
+ eval("@#{v}").expects(:purge)
+ ActiveRecord::Tasks::DatabaseTasks.purge 'adapter' => k
+ end
+ end
+ end
+
+ class DatabaseTasksCharsetTest < ActiveRecord::TestCase
+ include DatabaseTasksSetupper
+
+ ADAPTERS_TASKS.each do |k, v|
+ define_method("test_#{k}_charset") do
+ eval("@#{v}").expects(:charset)
+ ActiveRecord::Tasks::DatabaseTasks.charset 'adapter' => k
+ end
+ end
+ end
+
+ class DatabaseTasksCollationTest < ActiveRecord::TestCase
+ include DatabaseTasksSetupper
+
+ ADAPTERS_TASKS.each do |k, v|
+ define_method("test_#{k}_collation") do
+ eval("@#{v}").expects(:collation)
+ ActiveRecord::Tasks::DatabaseTasks.collation 'adapter' => k
+ end
+ end
+ end
+
+ class DatabaseTasksStructureDumpTest < ActiveRecord::TestCase
+ include DatabaseTasksSetupper
+
+ ADAPTERS_TASKS.each do |k, v|
+ define_method("test_#{k}_structure_dump") do
+ eval("@#{v}").expects(:structure_dump).with("awesome-file.sql")
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump({'adapter' => k}, "awesome-file.sql")
+ end
+ end
+ end
+
+ class DatabaseTasksStructureLoadTest < ActiveRecord::TestCase
+ include DatabaseTasksSetupper
+
+ ADAPTERS_TASKS.each do |k, v|
+ define_method("test_#{k}_structure_load") do
+ eval("@#{v}").expects(:structure_load).with("awesome-file.sql")
+ ActiveRecord::Tasks::DatabaseTasks.structure_load({'adapter' => k}, "awesome-file.sql")
+ end
+ end
+ end
+end
diff --git a/activerecord/test/cases/tasks/mysql_rake_test.rb b/activerecord/test/cases/tasks/mysql_rake_test.rb
new file mode 100644
index 0000000000..b49561d858
--- /dev/null
+++ b/activerecord/test/cases/tasks/mysql_rake_test.rb
@@ -0,0 +1,268 @@
+require 'cases/helper'
+
+module ActiveRecord
+ class MysqlDBCreateTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:create_database => true)
+ @configuration = {
+ 'adapter' => 'mysql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_establishes_connection_without_database
+ ActiveRecord::Base.expects(:establish_connection).
+ with('adapter' => 'mysql', 'database' => nil)
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_creates_database_with_default_options
+ @connection.expects(:create_database).
+ with('my-app-db', {:charset => 'utf8', :collation => 'utf8_unicode_ci'})
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_creates_database_with_given_options
+ @connection.expects(:create_database).
+ with('my-app-db', {:charset => 'latin', :collation => 'latin_ci'})
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration.merge(
+ 'charset' => 'latin', 'collation' => 'latin_ci'
+ )
+ end
+
+ def test_establishes_connection_to_database
+ ActiveRecord::Base.expects(:establish_connection).with(@configuration)
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+ end
+
+ class MysqlDBCreateAsRootTest < ActiveRecord::TestCase
+ def setup
+ unless current_adapter?(:MysqlAdapter)
+ return skip("only tested on mysql")
+ end
+
+ @connection = stub(:create_database => true, :execute => true)
+ @error = Mysql::Error.new "Invalid permissions"
+ @configuration = {
+ 'adapter' => 'mysql',
+ 'database' => 'my-app-db',
+ 'username' => 'pat',
+ 'password' => 'wossname'
+ }
+
+ $stdin.stubs(:gets).returns("secret\n")
+ $stdout.stubs(:print).returns(nil)
+ @error.stubs(:errno).returns(1045)
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).raises(@error).then.
+ returns(true)
+ end
+
+ def test_root_password_is_requested
+ skip "only if mysql is available" unless defined?(::Mysql)
+ $stdin.expects(:gets).returns("secret\n")
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_connection_established_as_root
+ ActiveRecord::Base.expects(:establish_connection).with({
+ 'adapter' => 'mysql',
+ 'database' => nil,
+ 'username' => 'root',
+ 'password' => 'secret'
+ })
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_database_created_by_root
+ @connection.expects(:create_database).
+ with('my-app-db', :charset => 'utf8', :collation => 'utf8_unicode_ci')
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_grant_privileges_for_normal_user
+ @connection.expects(:execute).with("GRANT ALL PRIVILEGES ON my-app-db.* TO 'pat'@'localhost' IDENTIFIED BY 'wossname' WITH GRANT OPTION;")
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_connection_established_as_normal_user
+ ActiveRecord::Base.expects(:establish_connection).returns do
+ ActiveRecord::Base.expects(:establish_connection).with({
+ 'adapter' => 'mysql',
+ 'database' => 'my-app-db',
+ 'username' => 'pat',
+ 'password' => 'secret'
+ })
+
+ raise @error
+ end
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_sends_output_to_stderr_when_other_errors
+ @error.stubs(:errno).returns(42)
+
+ $stderr.expects(:puts).at_least_once.returns(nil)
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+ end
+
+ class MySQLDBDropTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:drop_database => true)
+ @configuration = {
+ 'adapter' => 'mysql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_establishes_connection_to_mysql_database
+ ActiveRecord::Base.expects(:establish_connection).with @configuration
+
+ ActiveRecord::Tasks::DatabaseTasks.drop @configuration
+ end
+
+ def test_drops_database
+ @connection.expects(:drop_database).with('my-app-db')
+
+ ActiveRecord::Tasks::DatabaseTasks.drop @configuration
+ end
+ end
+
+ class MySQLPurgeTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:recreate_database => true)
+ @configuration = {
+ 'adapter' => 'mysql',
+ 'database' => 'test-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_establishes_connection_to_test_database
+ ActiveRecord::Base.expects(:establish_connection).with(:test)
+
+ ActiveRecord::Tasks::DatabaseTasks.purge @configuration
+ end
+
+ def test_recreates_database_with_the_default_options
+ @connection.expects(:recreate_database).
+ with('test-db', {:charset => 'utf8', :collation => 'utf8_unicode_ci'})
+
+ ActiveRecord::Tasks::DatabaseTasks.purge @configuration
+ end
+
+ def test_recreates_database_with_the_given_options
+ @connection.expects(:recreate_database).
+ with('test-db', {:charset => 'latin', :collation => 'latin_ci'})
+
+ ActiveRecord::Tasks::DatabaseTasks.purge @configuration.merge(
+ 'charset' => 'latin', 'collation' => 'latin_ci'
+ )
+ end
+ end
+
+ class MysqlDBCharsetTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:create_database => true)
+ @configuration = {
+ 'adapter' => 'mysql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_db_retrieves_charset
+ @connection.expects(:charset)
+ ActiveRecord::Tasks::DatabaseTasks.charset @configuration
+ end
+ end
+
+ class MysqlDBCollationTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:create_database => true)
+ @configuration = {
+ 'adapter' => 'mysql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_db_retrieves_collation
+ @connection.expects(:collation)
+ ActiveRecord::Tasks::DatabaseTasks.collation @configuration
+ end
+ end
+
+ class MySQLStructureDumpTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:structure_dump => true)
+ @configuration = {
+ 'adapter' => 'mysql',
+ 'database' => 'test-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_structure_dump
+ filename = "awesome-file.sql"
+ ActiveRecord::Base.expects(:establish_connection).with(@configuration)
+ @connection.expects(:structure_dump)
+
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, filename)
+ assert File.exists?(filename)
+ ensure
+ FileUtils.rm(filename)
+ end
+ end
+
+ class MySQLStructureLoadTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub
+ @configuration = {
+ 'adapter' => 'mysql',
+ 'database' => 'test-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_structure_load
+ filename = "awesome-file.sql"
+ ActiveRecord::Base.expects(:establish_connection).with(@configuration)
+ @connection.expects(:execute).twice
+
+ open(filename, 'w') { |f| f.puts("SELECT CURDATE();") }
+ ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename)
+ ensure
+ FileUtils.rm(filename)
+ end
+ end
+
+end
diff --git a/activerecord/test/cases/tasks/postgresql_rake_test.rb b/activerecord/test/cases/tasks/postgresql_rake_test.rb
new file mode 100644
index 0000000000..62acd53003
--- /dev/null
+++ b/activerecord/test/cases/tasks/postgresql_rake_test.rb
@@ -0,0 +1,226 @@
+require 'cases/helper'
+
+module ActiveRecord
+ class PostgreSQLDBCreateTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:create_database => true)
+ @configuration = {
+ 'adapter' => 'postgresql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_establishes_connection_to_postgresql_database
+ ActiveRecord::Base.expects(:establish_connection).with(
+ 'adapter' => 'postgresql',
+ 'database' => 'postgres',
+ 'schema_search_path' => 'public'
+ )
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_creates_database_with_default_encoding
+ @connection.expects(:create_database).
+ with('my-app-db', @configuration.merge('encoding' => 'utf8'))
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_creates_database_with_given_encoding
+ @connection.expects(:create_database).
+ with('my-app-db', @configuration.merge('encoding' => 'latin'))
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration.
+ merge('encoding' => 'latin')
+ end
+
+ def test_creates_database_with_given_collation_and_ctype
+ @connection.expects(:create_database).
+ with('my-app-db', @configuration.merge('encoding' => 'utf8', 'collation' => 'ja_JP.UTF8', 'ctype' => 'ja_JP.UTF8'))
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration.
+ merge('collation' => 'ja_JP.UTF8', 'ctype' => 'ja_JP.UTF8')
+ end
+
+ def test_establishes_connection_to_new_database
+ ActiveRecord::Base.expects(:establish_connection).with(@configuration)
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+
+ def test_db_create_with_error_prints_message
+ ActiveRecord::Base.stubs(:establish_connection).raises(Exception)
+
+ $stderr.stubs(:puts).returns(true)
+ $stderr.expects(:puts).
+ with("Couldn't create database for #{@configuration.inspect}")
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration
+ end
+ end
+
+ class PostgreSQLDBDropTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:drop_database => true)
+ @configuration = {
+ 'adapter' => 'postgresql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_establishes_connection_to_postgresql_database
+ ActiveRecord::Base.expects(:establish_connection).with(
+ 'adapter' => 'postgresql',
+ 'database' => 'postgres',
+ 'schema_search_path' => 'public'
+ )
+
+ ActiveRecord::Tasks::DatabaseTasks.drop @configuration
+ end
+
+ def test_drops_database
+ @connection.expects(:drop_database).with('my-app-db')
+
+ ActiveRecord::Tasks::DatabaseTasks.drop @configuration
+ end
+ end
+
+ class PostgreSQLPurgeTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:create_database => true, :drop_database => true)
+ @configuration = {
+ 'adapter' => 'postgresql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:clear_active_connections!).returns(true)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_clears_active_connections
+ ActiveRecord::Base.expects(:clear_active_connections!)
+
+ ActiveRecord::Tasks::DatabaseTasks.purge @configuration
+ end
+
+ def test_establishes_connection_to_postgresql_database
+ ActiveRecord::Base.expects(:establish_connection).with(
+ 'adapter' => 'postgresql',
+ 'database' => 'postgres',
+ 'schema_search_path' => 'public'
+ )
+
+ ActiveRecord::Tasks::DatabaseTasks.purge @configuration
+ end
+
+ def test_drops_database
+ @connection.expects(:drop_database).with('my-app-db')
+
+ ActiveRecord::Tasks::DatabaseTasks.purge @configuration
+ end
+
+ def test_creates_database
+ @connection.expects(:create_database).
+ with('my-app-db', @configuration.merge('encoding' => 'utf8'))
+
+ ActiveRecord::Tasks::DatabaseTasks.purge @configuration
+ end
+
+ def test_establishes_connection
+ ActiveRecord::Base.expects(:establish_connection).with(@configuration)
+
+ ActiveRecord::Tasks::DatabaseTasks.purge @configuration
+ end
+ end
+
+ class PostgreSQLDBCharsetTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:create_database => true)
+ @configuration = {
+ 'adapter' => 'postgresql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_db_retrieves_charset
+ @connection.expects(:encoding)
+ ActiveRecord::Tasks::DatabaseTasks.charset @configuration
+ end
+ end
+
+ class PostgreSQLDBCollationTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:create_database => true)
+ @configuration = {
+ 'adapter' => 'postgresql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_db_retrieves_collation
+ @connection.expects(:collation)
+ ActiveRecord::Tasks::DatabaseTasks.collation @configuration
+ end
+ end
+
+ class PostgreSQLStructureDumpTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub(:structure_dump => true)
+ @configuration = {
+ 'adapter' => 'postgresql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ Kernel.stubs(:system)
+ end
+
+ def test_structure_dump
+ filename = "awesome-file.sql"
+ Kernel.expects(:system).with("pg_dump -i -s -x -O -f #{filename} my-app-db").returns(true)
+ @connection.expects(:schema_search_path).returns("foo")
+
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump(@configuration, filename)
+ assert File.exists?(filename)
+ ensure
+ FileUtils.rm(filename)
+ end
+ end
+
+ class PostgreSQLStructureLoadTest < ActiveRecord::TestCase
+ def setup
+ @connection = stub
+ @configuration = {
+ 'adapter' => 'postgresql',
+ 'database' => 'my-app-db'
+ }
+
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ Kernel.stubs(:system)
+ end
+
+ def test_structure_dump
+ filename = "awesome-file.sql"
+ Kernel.expects(:system).with("psql -f #{filename} my-app-db")
+
+ ActiveRecord::Tasks::DatabaseTasks.structure_load(@configuration, filename)
+ end
+ end
+
+end
diff --git a/activerecord/test/cases/tasks/sqlite_rake_test.rb b/activerecord/test/cases/tasks/sqlite_rake_test.rb
new file mode 100644
index 0000000000..7209c0f14d
--- /dev/null
+++ b/activerecord/test/cases/tasks/sqlite_rake_test.rb
@@ -0,0 +1,191 @@
+require 'cases/helper'
+require 'pathname'
+
+module ActiveRecord
+ class SqliteDBCreateTest < ActiveRecord::TestCase
+ def setup
+ @database = 'db_create.sqlite3'
+ @connection = stub :connection
+ @configuration = {
+ 'adapter' => 'sqlite3',
+ 'database' => @database
+ }
+
+ File.stubs(:exist?).returns(false)
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_db_checks_database_exists
+ File.expects(:exist?).with(@database).returns(false)
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root'
+ end
+
+ def test_db_create_when_file_exists
+ File.stubs(:exist?).returns(true)
+
+ $stderr.expects(:puts).with("#{@database} already exists")
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root'
+ end
+
+ def test_db_create_with_file_does_nothing
+ File.stubs(:exist?).returns(true)
+ $stderr.stubs(:puts).returns(nil)
+
+ ActiveRecord::Base.expects(:establish_connection).never
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root'
+ end
+
+ def test_db_create_establishes_a_connection
+ ActiveRecord::Base.expects(:establish_connection).with(@configuration)
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root'
+ end
+
+ def test_db_create_with_error_prints_message
+ ActiveRecord::Base.stubs(:establish_connection).raises(Exception)
+
+ $stderr.stubs(:puts).returns(true)
+ $stderr.expects(:puts).
+ with("Couldn't create database for #{@configuration.inspect}")
+
+ ActiveRecord::Tasks::DatabaseTasks.create @configuration, '/rails/root'
+ end
+ end
+
+ class SqliteDBDropTest < ActiveRecord::TestCase
+ def setup
+ @database = "db_create.sqlite3"
+ @path = stub(:to_s => '/absolute/path', :absolute? => true)
+ @configuration = {
+ 'adapter' => 'sqlite3',
+ 'database' => @database
+ }
+
+ Pathname.stubs(:new).returns(@path)
+ File.stubs(:join).returns('/former/relative/path')
+ FileUtils.stubs(:rm).returns(true)
+ end
+
+ def test_creates_path_from_database
+ Pathname.expects(:new).with(@database).returns(@path)
+
+ ActiveRecord::Tasks::DatabaseTasks.drop @configuration, '/rails/root'
+ end
+
+ def test_removes_file_with_absolute_path
+ File.stubs(:exist?).returns(true)
+ @path.stubs(:absolute?).returns(true)
+
+ FileUtils.expects(:rm).with('/absolute/path')
+
+ ActiveRecord::Tasks::DatabaseTasks.drop @configuration, '/rails/root'
+ end
+
+ def test_generates_absolute_path_with_given_root
+ @path.stubs(:absolute?).returns(false)
+
+ File.expects(:join).with('/rails/root', @path).
+ returns('/former/relative/path')
+
+ ActiveRecord::Tasks::DatabaseTasks.drop @configuration, '/rails/root'
+ end
+
+ def test_removes_file_with_relative_path
+ File.stubs(:exist?).returns(true)
+ @path.stubs(:absolute?).returns(false)
+
+ FileUtils.expects(:rm).with('/former/relative/path')
+
+ ActiveRecord::Tasks::DatabaseTasks.drop @configuration, '/rails/root'
+ end
+ end
+
+ class SqliteDBCharsetTest < ActiveRecord::TestCase
+ def setup
+ @database = 'db_create.sqlite3'
+ @connection = stub :connection
+ @configuration = {
+ 'adapter' => 'sqlite3',
+ 'database' => @database
+ }
+
+ File.stubs(:exist?).returns(false)
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_db_retrieves_charset
+ @connection.expects(:encoding)
+ ActiveRecord::Tasks::DatabaseTasks.charset @configuration, '/rails/root'
+ end
+ end
+
+ class SqliteDBCollationTest < ActiveRecord::TestCase
+ def setup
+ @database = 'db_create.sqlite3'
+ @connection = stub :connection
+ @configuration = {
+ 'adapter' => 'sqlite3',
+ 'database' => @database
+ }
+
+ File.stubs(:exist?).returns(false)
+ ActiveRecord::Base.stubs(:connection).returns(@connection)
+ ActiveRecord::Base.stubs(:establish_connection).returns(true)
+ end
+
+ def test_db_retrieves_collation
+ assert_raise NoMethodError do
+ ActiveRecord::Tasks::DatabaseTasks.collation @configuration, '/rails/root'
+ end
+ end
+ end
+
+ class SqliteStructureDumpTest < ActiveRecord::TestCase
+ def setup
+ @database = "db_create.sqlite3"
+ @configuration = {
+ 'adapter' => 'sqlite3',
+ 'database' => @database
+ }
+ end
+
+ def test_structure_dump
+ dbfile = @database
+ filename = "awesome-file.sql"
+
+ ActiveRecord::Tasks::DatabaseTasks.structure_dump @configuration, filename, '/rails/root'
+ assert File.exists?(dbfile)
+ assert File.exists?(filename)
+ ensure
+ FileUtils.rm_f(filename)
+ FileUtils.rm_f(dbfile)
+ end
+ end
+
+ class SqliteStructureLoadTest < ActiveRecord::TestCase
+ def setup
+ @database = "db_create.sqlite3"
+ @configuration = {
+ 'adapter' => 'sqlite3',
+ 'database' => @database
+ }
+ end
+
+ def test_structure_load
+ dbfile = @database
+ filename = "awesome-file.sql"
+
+ open(filename, 'w') { |f| f.puts("select datetime('now', 'localtime');") }
+ ActiveRecord::Tasks::DatabaseTasks.structure_load @configuration, filename, '/rails/root'
+ assert File.exists?(dbfile)
+ ensure
+ FileUtils.rm_f(filename)
+ FileUtils.rm_f(dbfile)
+ end
+ end
+end
diff --git a/activerecord/test/cases/test_case.rb b/activerecord/test/cases/test_case.rb
index 94a13d386c..f3f7054794 100644
--- a/activerecord/test/cases/test_case.rb
+++ b/activerecord/test/cases/test_case.rb
@@ -1,4 +1,3 @@
-require 'active_support/deprecation'
ActiveSupport::Deprecation.silence do
require 'active_record/test_case'
end
diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb
index 447aa29ffe..bb034848e1 100644
--- a/activerecord/test/cases/timestamp_test.rb
+++ b/activerecord/test/cases/timestamp_test.rb
@@ -11,7 +11,7 @@ class TimestampTest < ActiveRecord::TestCase
def setup
@developer = Developer.first
- @developer.update_attribute(:updated_at, Time.now.prev_month)
+ @developer.update_columns(updated_at: Time.now.prev_month)
@previously_updated_at = @developer.updated_at
end
@@ -114,9 +114,12 @@ class TimestampTest < ActiveRecord::TestCase
end
def test_saving_a_record_with_a_belongs_to_that_specifies_touching_a_specific_attribute_the_parent_should_update_that_attribute
- Pet.belongs_to :owner, :touch => :happy_at
+ klass = Class.new(ActiveRecord::Base) do
+ def self.name; 'Pet'; end
+ belongs_to :owner, :touch => :happy_at
+ end
- pet = Pet.first
+ pet = klass.first
owner = pet.owner
previously_owner_happy_at = owner.happy_at
@@ -124,42 +127,41 @@ class TimestampTest < ActiveRecord::TestCase
pet.save
assert_not_equal previously_owner_happy_at, pet.owner.happy_at
- ensure
- Pet.belongs_to :owner, :touch => true
end
def test_touching_a_record_with_a_belongs_to_that_uses_a_counter_cache_should_update_the_parent
- Pet.belongs_to :owner, :counter_cache => :use_count, :touch => true
+ klass = Class.new(ActiveRecord::Base) do
+ def self.name; 'Pet'; end
+ belongs_to :owner, :counter_cache => :use_count, :touch => true
+ end
- pet = Pet.first
+ pet = klass.first
owner = pet.owner
- owner.update_attribute(:happy_at, 3.days.ago)
+ owner.update_columns(happy_at: 3.days.ago)
previously_owner_updated_at = owner.updated_at
pet.name = "I'm a parrot"
pet.save
assert_not_equal previously_owner_updated_at, pet.owner.updated_at
- ensure
- Pet.belongs_to :owner, :touch => true
end
def test_touching_a_record_touches_parent_record_and_grandparent_record
- Toy.belongs_to :pet, :touch => true
- Pet.belongs_to :owner, :touch => true
+ klass = Class.new(ActiveRecord::Base) do
+ def self.name; 'Toy'; end
+ belongs_to :pet, :touch => true
+ end
- toy = Toy.first
+ toy = klass.first
pet = toy.pet
owner = pet.owner
time = 3.days.ago
- owner.update_column(:updated_at, time)
+ owner.update_columns(updated_at: time)
toy.touch
owner.reload
assert_not_equal time, owner.updated_at
- ensure
- Toy.belongs_to :pet
end
def test_timestamp_attributes_for_create
diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb
index a9ccd00fac..0d0de455b3 100644
--- a/activerecord/test/cases/transactions_test.rb
+++ b/activerecord/test/cases/transactions_test.rb
@@ -91,18 +91,14 @@ class TransactionTest < ActiveRecord::TestCase
end
def test_raising_exception_in_callback_rollbacks_in_save
- add_exception_raising_after_save_callback_to_topic
-
- begin
- @first.approved = true
- @first.save
- flunk
- rescue => e
- assert_equal "Make the transaction rollback", e.message
- assert !Topic.find(1).approved?
- ensure
- remove_exception_raising_after_save_callback_to_topic
+ def @first.after_save_for_transaction
+ raise 'Make the transaction rollback'
end
+
+ @first.approved = true
+ e = assert_raises(RuntimeError) { @first.save }
+ assert_equal "Make the transaction rollback", e.message
+ assert !Topic.find(1).approved?
end
def test_update_attributes_should_rollback_on_failure
@@ -125,85 +121,85 @@ class TransactionTest < ActiveRecord::TestCase
end
def test_cancellation_from_before_destroy_rollbacks_in_destroy
- add_cancelling_before_destroy_with_db_side_effect_to_topic
- begin
- nbooks_before_destroy = Book.count
- status = @first.destroy
- assert !status
- assert_nothing_raised(ActiveRecord::RecordNotFound) { @first.reload }
- assert_equal nbooks_before_destroy, Book.count
- ensure
- remove_cancelling_before_destroy_with_db_side_effect_to_topic
- end
+ add_cancelling_before_destroy_with_db_side_effect_to_topic @first
+ nbooks_before_destroy = Book.count
+ status = @first.destroy
+ assert !status
+ @first.reload
+ assert_equal nbooks_before_destroy, Book.count
end
- def test_cancellation_from_before_filters_rollbacks_in_save
- %w(validation save).each do |filter|
- send("add_cancelling_before_#{filter}_with_db_side_effect_to_topic")
- begin
- nbooks_before_save = Book.count
- original_author_name = @first.author_name
- @first.author_name += '_this_should_not_end_up_in_the_db'
- status = @first.save
- assert !status
- assert_equal original_author_name, @first.reload.author_name
- assert_equal nbooks_before_save, Book.count
- ensure
- send("remove_cancelling_before_#{filter}_with_db_side_effect_to_topic")
- end
+ %w(validation save).each do |filter|
+ define_method("test_cancellation_from_before_filters_rollbacks_in_#{filter}") do
+ send("add_cancelling_before_#{filter}_with_db_side_effect_to_topic", @first)
+ nbooks_before_save = Book.count
+ original_author_name = @first.author_name
+ @first.author_name += '_this_should_not_end_up_in_the_db'
+ status = @first.save
+ assert !status
+ assert_equal original_author_name, @first.reload.author_name
+ assert_equal nbooks_before_save, Book.count
end
- end
- def test_cancellation_from_before_filters_rollbacks_in_save!
- %w(validation save).each do |filter|
- send("add_cancelling_before_#{filter}_with_db_side_effect_to_topic")
+ define_method("test_cancellation_from_before_filters_rollbacks_in_#{filter}!") do
+ send("add_cancelling_before_#{filter}_with_db_side_effect_to_topic", @first)
+ nbooks_before_save = Book.count
+ original_author_name = @first.author_name
+ @first.author_name += '_this_should_not_end_up_in_the_db'
+
begin
- nbooks_before_save = Book.count
- original_author_name = @first.author_name
- @first.author_name += '_this_should_not_end_up_in_the_db'
@first.save!
- flunk
- rescue
- assert_equal original_author_name, @first.reload.author_name
- assert_equal nbooks_before_save, Book.count
- ensure
- send("remove_cancelling_before_#{filter}_with_db_side_effect_to_topic")
+ rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved
end
+
+ assert_equal original_author_name, @first.reload.author_name
+ assert_equal nbooks_before_save, Book.count
end
end
def test_callback_rollback_in_create
- new_topic = Topic.new(
- :title => "A new topic",
- :author_name => "Ben",
- :author_email_address => "ben@example.com",
- :written_on => "2003-07-16t15:28:11.2233+01:00",
- :last_read => "2004-04-15",
- :bonus_time => "2005-01-30t15:28:00.00+01:00",
- :content => "Have a nice day",
- :approved => false)
+ topic = Class.new(Topic) {
+ def after_create_for_transaction
+ raise 'Make the transaction rollback'
+ end
+ }
+
+ new_topic = topic.new(:title => "A new topic",
+ :author_name => "Ben",
+ :author_email_address => "ben@example.com",
+ :written_on => "2003-07-16t15:28:11.2233+01:00",
+ :last_read => "2004-04-15",
+ :bonus_time => "2005-01-30t15:28:00.00+01:00",
+ :content => "Have a nice day",
+ :approved => false)
+
new_record_snapshot = !new_topic.persisted?
id_present = new_topic.has_attribute?(Topic.primary_key)
id_snapshot = new_topic.id
# Make sure the second save gets the after_create callback called.
2.times do
- begin
- add_exception_raising_after_create_callback_to_topic
- new_topic.approved = true
- new_topic.save
- flunk
- rescue => e
- assert_equal "Make the transaction rollback", e.message
- assert_equal new_record_snapshot, !new_topic.persisted?, "The topic should have its old persisted value"
- assert_equal id_snapshot, new_topic.id, "The topic should have its old id"
- assert_equal id_present, new_topic.has_attribute?(Topic.primary_key)
- ensure
- remove_exception_raising_after_create_callback_to_topic
- end
+ new_topic.approved = true
+ e = assert_raises(RuntimeError) { new_topic.save }
+ assert_equal "Make the transaction rollback", e.message
+ assert_equal new_record_snapshot, !new_topic.persisted?, "The topic should have its old persisted value"
+ assert_equal id_snapshot, new_topic.id, "The topic should have its old id"
+ assert_equal id_present, new_topic.has_attribute?(Topic.primary_key)
end
end
+ def test_callback_rollback_in_create_with_record_invalid_exception
+ topic = Class.new(Topic) {
+ def after_create_for_transaction
+ raise ActiveRecord::RecordInvalid.new(Author.new)
+ end
+ }
+
+ new_topic = topic.create(:title => "A new topic")
+ assert !new_topic.persisted?, "The topic should not be persisted"
+ assert_nil new_topic.id, "The topic should not have an ID"
+ end
+
def test_nested_explicit_transactions
Topic.transaction do
Topic.transaction do
@@ -461,62 +457,16 @@ class TransactionTest < ActiveRecord::TestCase
end
private
- def define_callback_method(callback_method)
- define_method(callback_method) do
- self.history << [callback_method, :method]
- end
- end
- def add_exception_raising_after_save_callback_to_topic
- Topic.class_eval <<-eoruby, __FILE__, __LINE__ + 1
- remove_method(:after_save_for_transaction)
- def after_save_for_transaction
- raise 'Make the transaction rollback'
- end
- eoruby
- end
-
- def remove_exception_raising_after_save_callback_to_topic
- Topic.class_eval <<-eoruby, __FILE__, __LINE__ + 1
- remove_method :after_save_for_transaction
- def after_save_for_transaction; end
- eoruby
- end
-
- def add_exception_raising_after_create_callback_to_topic
- Topic.class_eval <<-eoruby, __FILE__, __LINE__ + 1
- remove_method(:after_create_for_transaction)
- def after_create_for_transaction
- raise 'Make the transaction rollback'
- end
- eoruby
- end
-
- def remove_exception_raising_after_create_callback_to_topic
- Topic.class_eval <<-eoruby, __FILE__, __LINE__ + 1
- remove_method :after_create_for_transaction
- def after_create_for_transaction; end
- eoruby
- end
-
- %w(validation save destroy).each do |filter|
- define_method("add_cancelling_before_#{filter}_with_db_side_effect_to_topic") do
- Topic.class_eval <<-eoruby, __FILE__, __LINE__ + 1
- remove_method :before_#{filter}_for_transaction
- def before_#{filter}_for_transaction
- Book.create
- false
- end
- eoruby
- end
-
- define_method("remove_cancelling_before_#{filter}_with_db_side_effect_to_topic") do
- Topic.class_eval <<-eoruby, __FILE__, __LINE__ + 1
- remove_method :before_#{filter}_for_transaction
- def before_#{filter}_for_transaction; end
- eoruby
+ %w(validation save destroy).each do |filter|
+ define_method("add_cancelling_before_#{filter}_with_db_side_effect_to_topic") do |topic|
+ meta = class << topic; self; end
+ meta.send("define_method", "before_#{filter}_for_transaction") do
+ Book.create
+ false
end
end
+ end
end
class TransactionsWithTransactionalFixturesTest < ActiveRecord::TestCase
diff --git a/activerecord/test/cases/validations/presence_validation_test.rb b/activerecord/test/cases/validations/presence_validation_test.rb
new file mode 100644
index 0000000000..cd9175f454
--- /dev/null
+++ b/activerecord/test/cases/validations/presence_validation_test.rb
@@ -0,0 +1,44 @@
+# encoding: utf-8
+require "cases/helper"
+require 'models/man'
+require 'models/face'
+require 'models/interest'
+
+class PresenceValidationTest < ActiveRecord::TestCase
+ class Boy < Man; end
+
+ repair_validations(Boy)
+
+ def test_validates_presence_of_non_association
+ Boy.validates_presence_of(:name)
+ b = Boy.new
+ assert b.invalid?
+
+ b.name = "Alex"
+ assert b.valid?
+ end
+
+ def test_validates_presence_of_has_one_marked_for_destruction
+ Boy.validates_presence_of(:face)
+ b = Boy.new
+ f = Face.new
+ b.face = f
+ assert b.valid?
+
+ f.mark_for_destruction
+ assert b.invalid?
+ end
+
+ def test_validates_presence_of_has_many_marked_for_destruction
+ Boy.validates_presence_of(:interests)
+ b = Boy.new
+ b.interests << [i1 = Interest.new, i2 = Interest.new]
+ assert b.valid?
+
+ i1.mark_for_destruction
+ assert b.valid?
+
+ i2.mark_for_destruction
+ assert b.invalid?
+ end
+end
diff --git a/activerecord/test/cases/validations/uniqueness_validation_test.rb b/activerecord/test/cases/validations/uniqueness_validation_test.rb
index c173ee9a15..46212e49b6 100644
--- a/activerecord/test/cases/validations/uniqueness_validation_test.rb
+++ b/activerecord/test/cases/validations/uniqueness_validation_test.rb
@@ -22,6 +22,14 @@ end
class Thaumaturgist < IneptWizard
end
+class ReplyTitle; end
+
+class ReplyWithTitleObject < Reply
+ validates_uniqueness_of :content, :scope => :title
+
+ def title; ReplyTitle.new; end
+end
+
class UniquenessValidationTest < ActiveRecord::TestCase
fixtures :topics, 'warehouse-things', :developers
@@ -104,6 +112,14 @@ class UniquenessValidationTest < ActiveRecord::TestCase
assert !r2.valid?, "Saving r2 first time"
end
+ def test_validate_uniqueness_with_composed_attribute_scope
+ r1 = ReplyWithTitleObject.create "title" => "r1", "content" => "hello world"
+ assert r1.valid?, "Saving r1"
+
+ r2 = ReplyWithTitleObject.create "title" => "r1", "content" => "hello world"
+ assert !r2.valid?, "Saving r2 first time"
+ end
+
def test_validate_uniqueness_with_object_arg
Reply.validates_uniqueness_of(:topic)
@@ -189,7 +205,7 @@ class UniquenessValidationTest < ActiveRecord::TestCase
assert t_utf8.save, "Should save t_utf8 as unique"
# If database hasn't UTF-8 character set, this test fails
- if Topic.scoped(:select => 'LOWER(title) AS title').find(t_utf8).title == "я тоже уникальный!"
+ if Topic.all.merge!(:select => 'LOWER(title) AS title').find(t_utf8).title == "я тоже уникальный!"
t2_utf8 = Topic.new("title" => "я тоже УНИКАЛЬНЫЙ!")
assert !t2_utf8.valid?, "Shouldn't be valid"
assert !t2_utf8.save, "Shouldn't save t2_utf8 as unique"
diff --git a/activerecord/test/cases/xml_serialization_test.rb b/activerecord/test/cases/xml_serialization_test.rb
index 12373333b0..7249ae9e4d 100644
--- a/activerecord/test/cases/xml_serialization_test.rb
+++ b/activerecord/test/cases/xml_serialization_test.rb
@@ -74,33 +74,88 @@ end
class DefaultXmlSerializationTest < ActiveRecord::TestCase
def setup
- @xml = Contact.new(:name => 'aaron stack', :age => 25, :avatar => 'binarydata', :created_at => Time.utc(2006, 8, 1), :awesome => false, :preferences => { :gem => 'ruby' }).to_xml
+ @contact = Contact.new(
+ :name => 'aaron stack',
+ :age => 25,
+ :avatar => 'binarydata',
+ :created_at => Time.utc(2006, 8, 1),
+ :awesome => false,
+ :preferences => { :gem => 'ruby' }
+ )
end
def test_should_serialize_string
- assert_match %r{<name>aaron stack</name>}, @xml
+ assert_match %r{<name>aaron stack</name>}, @contact.to_xml
end
def test_should_serialize_integer
- assert_match %r{<age type="integer">25</age>}, @xml
+ assert_match %r{<age type="integer">25</age>}, @contact.to_xml
end
def test_should_serialize_binary
- assert_match %r{YmluYXJ5ZGF0YQ==\n</avatar>}, @xml
- assert_match %r{<avatar(.*)(type="binary")}, @xml
- assert_match %r{<avatar(.*)(encoding="base64")}, @xml
+ xml = @contact.to_xml
+ assert_match %r{YmluYXJ5ZGF0YQ==\n</avatar>}, xml
+ assert_match %r{<avatar(.*)(type="binary")}, xml
+ assert_match %r{<avatar(.*)(encoding="base64")}, xml
end
def test_should_serialize_datetime
- assert_match %r{<created-at type=\"dateTime\">2006-08-01T00:00:00Z</created-at>}, @xml
+ assert_match %r{<created-at type=\"dateTime\">2006-08-01T00:00:00Z</created-at>}, @contact.to_xml
end
def test_should_serialize_boolean
- assert_match %r{<awesome type=\"boolean\">false</awesome>}, @xml
+ assert_match %r{<awesome type=\"boolean\">false</awesome>}, @contact.to_xml
end
def test_should_serialize_hash
- assert_match %r{<preferences>\s*<gem>ruby</gem>\s*</preferences>}m, @xml
+ assert_match %r{<preferences>\s*<gem>ruby</gem>\s*</preferences>}m, @contact.to_xml
+ end
+
+ def test_uses_serializable_hash_with_only_option
+ def @contact.serializable_hash(options=nil)
+ super(only: %w(name))
+ end
+
+ xml = @contact.to_xml
+ assert_match %r{<name>aaron stack</name>}, xml
+ assert_no_match %r{age}, xml
+ assert_no_match %r{awesome}, xml
+ end
+
+ def test_uses_serializable_hash_with_except_option
+ def @contact.serializable_hash(options=nil)
+ super(except: %w(age))
+ end
+
+ xml = @contact.to_xml
+ assert_match %r{<name>aaron stack</name>}, xml
+ assert_match %r{<awesome type=\"boolean\">false</awesome>}, xml
+ assert_no_match %r{age}, xml
+ end
+
+ def test_does_not_include_inheritance_column_from_sti
+ @contact = ContactSti.new(@contact.attributes)
+ assert_equal 'ContactSti', @contact.type
+
+ xml = @contact.to_xml
+ assert_match %r{<name>aaron stack</name>}, xml
+ assert_no_match %r{<type}, xml
+ assert_no_match %r{ContactSti}, xml
+ end
+
+ def test_serializable_hash_with_default_except_option_and_excluding_inheritance_column_from_sti
+ @contact = ContactSti.new(@contact.attributes)
+ assert_equal 'ContactSti', @contact.type
+
+ def @contact.serializable_hash(options={})
+ super({ except: %w(age) }.merge!(options))
+ end
+
+ xml = @contact.to_xml
+ assert_match %r{<name>aaron stack</name>}, xml
+ assert_no_match %r{age}, xml
+ assert_no_match %r{<type}, xml
+ assert_no_match %r{ContactSti}, xml
end
end