modernizes hash syntax in activerecord

This commit is contained in:
Xavier Noria 2016-08-06 19:37:57 +02:00
parent fa911a74e1
commit d22e522179
202 changed files with 2398 additions and 2402 deletions

@ -18,7 +18,7 @@ def run_without_aborting(*tasks)
end
desc "Run mysql2, sqlite, and postgresql tests by default"
task :default => :test
task default: :test
task :package
@ -41,8 +41,8 @@ end
desc "Build MySQL and PostgreSQL test databases"
namespace :db do
task :create => ["db:mysql:build", "db:postgresql:build"]
task :drop => ["db:mysql:drop", "db:postgresql:drop"]
task create: ["db:mysql:build", "db:postgresql:build"]
task drop: ["db:mysql:drop", "db:postgresql:drop"]
end
%w( mysql2 postgresql sqlite3 sqlite3_mem db2 oracle jdbcmysql jdbcpostgresql jdbcsqlite3 jdbcderby jdbch2 jdbchsqldb ).each do |adapter|
@ -73,8 +73,8 @@ end
end
namespace adapter do
task :test => "test_#{adapter}"
task :isolated_test => "isolated_test_#{adapter}"
task test: "test_#{adapter}"
task isolated_test: "isolated_test_#{adapter}"
# Set the connection environment for the adapter
task(:env) { ENV["ARCONN"] = adapter }
@ -102,7 +102,7 @@ namespace :db do
end
desc "Rebuild the MySQL test databases"
task :rebuild => [:drop, :build]
task rebuild: [:drop, :build]
end
namespace :postgresql do
@ -126,17 +126,17 @@ namespace :db do
end
desc "Rebuild the PostgreSQL test databases"
task :rebuild => [:drop, :build]
task rebuild: [:drop, :build]
end
end
task :build_mysql_databases => "db:mysql:build"
task :drop_mysql_databases => "db:mysql:drop"
task :rebuild_mysql_databases => "db:mysql:rebuild"
task build_mysql_databases: "db:mysql:build"
task drop_mysql_databases: "db:mysql:drop"
task rebuild_mysql_databases: "db:mysql:rebuild"
task :build_postgresql_databases => "db:postgresql:build"
task :drop_postgresql_databases => "db:postgresql:drop"
task :rebuild_postgresql_databases => "db:postgresql:rebuild"
task build_postgresql_databases: "db:postgresql:build"
task drop_postgresql_databases: "db:postgresql:drop"
task rebuild_postgresql_databases: "db:postgresql:rebuild"
task :lines do
load File.expand_path("..", File.dirname(__FILE__)) + "/tools/line_statistics"

@ -90,7 +90,7 @@ def initialize(reflection = nil)
through_reflection = reflection.through_reflection
source_reflection_names = reflection.source_reflection_names
source_associations = reflection.through_reflection.klass._reflections.keys
super("Could not find the source association(s) #{source_reflection_names.collect(&:inspect).to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => <name>'. Is it one of #{source_associations.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)}?")
super("Could not find the source association(s) #{source_reflection_names.collect(&:inspect).to_sentence(two_words_connector: ' or ', last_word_connector: ', or ', locale: :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => <name>'. Is it one of #{source_associations.to_sentence(two_words_connector: ' or ', last_word_connector: ', or ', locale: :en)}?")
else
super("Could not find the source association(s).")
end

@ -19,7 +19,7 @@ class Association #:nodoc:
attr_reader :owner, :target, :reflection
attr_accessor :inversed
delegate :options, :to => :reflection
delegate :options, to: :reflection
def initialize(owner, reflection)
reflection.check_validity!

@ -41,9 +41,9 @@ def insert_record(record, validate = true, raise = false)
set_inverse_instance(record)
if raise
record.save!(:validate => validate)
record.save!(validate: validate)
else
record.save(:validate => validate)
record.save(validate: validate)
end
end

@ -39,9 +39,9 @@ def insert_record(record, validate = true, raise = false)
ensure_not_nested
if raise
record.save!(:validate => validate)
record.save!(validate: validate)
else
return unless record.save(:validate => validate)
return unless record.save(validate: validate)
end
save_through_record(record)

@ -15,7 +15,7 @@ class JoinPart # :nodoc:
# association.
attr_reader :base_klass, :children
delegate :table_name, :column_names, :primary_key, :to => :base_klass
delegate :table_name, :column_names, :primary_key, to: :base_klass
def initialize(base_klass, children)
@base_klass = base_klass

@ -3,7 +3,7 @@ module ActiveRecord
module Associations
module ThroughAssociation #:nodoc:
delegate :source_reflection, :through_reflection, :to => :reflection
delegate :source_reflection, :through_reflection, to: :reflection
protected

@ -400,7 +400,7 @@ def save_collection_association(reflection)
association.insert_record(record) unless reflection.nested?
end
elsif autosave
saved = record.save(:validate => false)
saved = record.save(validate: false)
end
raise ActiveRecord::Rollback unless saved
@ -437,7 +437,7 @@ def save_has_one_association(reflection)
record[reflection.foreign_key] = key
end
saved = record.save(:validate => !autosave)
saved = record.save(validate: !autosave)
raise ActiveRecord::Rollback if !saved && autosave
saved
end
@ -465,7 +465,7 @@ def save_belongs_to_association(reflection)
self[reflection.foreign_key] = nil
record.destroy
elsif autosave != false
saved = record.save(:validate => !autosave) if record.new_record? || (autosave && record.changed_for_autosave?)
saved = record.save(validate: !autosave) if record.new_record? || (autosave && record.changed_for_autosave?)
if association.updated?
association_id = record.send(reflection.options[:primary_key] || :id)

@ -272,7 +272,7 @@ module ClassMethods # :nodoc:
included do
include ActiveModel::Validations::Callbacks
define_model_callbacks :initialize, :find, :touch, :only => :after
define_model_callbacks :initialize, :find, :touch, only: :after
define_model_callbacks :save, :create, :update, :destroy
end

@ -339,7 +339,7 @@ def initialize(spec)
# that case +conn.owner+ attr should be consulted.
# Access and modification of +@thread_cached_conns+ does not require
# synchronization.
@thread_cached_conns = Concurrent::Map.new(:initial_capacity => @size)
@thread_cached_conns = Concurrent::Map.new(initial_capacity: @size)
@connections = []
@automatic_reconnect = true
@ -833,8 +833,8 @@ def checkout_and_verify(c)
class ConnectionHandler
def initialize
# These caches are keyed by spec.name (ConnectionSpecification#name).
@owner_to_pool = Concurrent::Map.new(:initial_capacity => 2) do |h,k|
h[k] = Concurrent::Map.new(:initial_capacity => 2)
@owner_to_pool = Concurrent::Map.new(initial_capacity: 2) do |h,k|
h[k] = Concurrent::Map.new(initial_capacity: 2)
end
end

@ -77,7 +77,7 @@ def cache_sql(sql, binds)
result =
if @query_cache[sql].key?(binds)
ActiveSupport::Notifications.instrument("sql.active_record",
:sql => sql, :binds => binds, :name => "CACHE", :connection_id => object_id)
sql: sql, binds: binds, name: "CACHE", connection_id: object_id)
@query_cache[sql][binds]
else
@query_cache[sql][binds] = yield

@ -762,7 +762,7 @@ def index_name(table_name, options) #:nodoc:
raise ArgumentError, "You must specify the index name"
end
else
index_name(table_name, :column => options)
index_name(table_name, column: options)
end
end

@ -480,7 +480,7 @@ def rename_index(table_name, old_name, new_name)
def change_column_default(table_name, column_name, default_or_changes) #:nodoc:
default = extract_new_default_value(default_or_changes)
column = column_for(table_name, column_name)
change_column table_name, column_name, column.sql_type, :default => default
change_column table_name, column_name, column.sql_type, default: default
end
def change_column_null(table_name, column_name, null, default = nil) #:nodoc:
@ -490,7 +490,7 @@ def change_column_null(table_name, column_name, null, default = nil) #:nodoc:
execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL")
end
change_column table_name, column_name, column.sql_type, :null => null
change_column table_name, column_name, column.sql_type, null: null
end
def change_column(table_name, column_name, type, options = {}) #:nodoc:

@ -65,7 +65,7 @@ def supports_savepoints?
def each_hash(result) # :nodoc:
if block_given?
result.each(:as => :hash, :symbolize_keys => true) do |row|
result.each(as: :hash, symbolize_keys: true) do |row|
yield row
end
else
@ -119,7 +119,7 @@ def connect
end
def configure_connection
@connection.query_options.merge!(:as => :array)
@connection.query_options.merge!(as: :array)
super
end

@ -33,7 +33,7 @@ def data_source_exists?(name)
@data_sources[name] = connection.data_source_exists?(name)
end
alias table_exists? data_source_exists?
deprecate :table_exists? => "use #data_source_exists? instead"
deprecate table_exists?: "use #data_source_exists? instead"
# Add internal cache for table with +table_name+.
@ -49,7 +49,7 @@ def data_sources(name)
@data_sources[name]
end
alias tables data_sources
deprecate :tables => "use #data_sources instead"
deprecate tables: "use #data_sources instead"
# Get the columns for a table
def columns(table_name)
@ -85,7 +85,7 @@ def clear_data_source_cache!(name)
@data_sources.delete name
end
alias clear_table_cache! clear_data_source_cache!
deprecate :clear_table_cache! => "use #clear_data_source_cache! instead"
deprecate clear_table_cache!: "use #clear_data_source_cache! instead"
def marshal_dump
# if we get current version during initialization, it happens stack over flow.

@ -26,7 +26,7 @@ def sqlite3_connection(config)
db = SQLite3::Database.new(
config[:database].to_s,
:results_as_hash => true
results_as_hash: true
)
db.busy_timeout(ConnectionAdapters::SQLite3Adapter.type_cast_config_to_integer(config[:timeout])) if config[:timeout]
@ -205,7 +205,7 @@ def exec_query(sql, name = nil, binds = [], prepare: false)
end
else
cache = @statements[sql] ||= {
:stmt => @connection.prepare(sql)
stmt: @connection.prepare(sql)
}
stmt = cache[:stmt]
cols = cache[:cols] ||= stmt.columns
@ -436,7 +436,7 @@ def alter_table(table_name, options = {}) #:nodoc:
transaction do
move_table(table_name, altered_table_name,
options.merge(:temporary => true))
options.merge(temporary: true))
move_table(altered_table_name, table_name, &caller)
end
end
@ -460,9 +460,9 @@ def copy_table(from, to, options = {}) #:nodoc:
next if column_name == from_primary_key
@definition.column(column_name, column.type,
:limit => column.limit, :default => column.default,
:precision => column.precision, :scale => column.scale,
:null => column.null, collation: column.collation)
limit: column.limit, default: column.default,
precision: column.precision, scale: column.scale,
null: column.null, collation: column.collation)
end
yield @definition if block_given?
end

@ -138,6 +138,6 @@ def clear_cache! # :nodoc:
end
delegate :clear_active_connections!, :clear_reloadable_connections!,
:clear_all_connections!, :to => :connection_handler
:clear_all_connections!, to: :connection_handler
end
end

@ -535,7 +535,7 @@ def self.create_fixtures(fixtures_directory, fixture_set_names, class_names = {}
update_all_loaded_fixtures fixtures_map
connection.transaction(:requires_new => true) do
connection.transaction(requires_new: true) do
deleted_tables = Set.new
fixture_sets.each do |fs|
conn = fs.model_class.respond_to?(:connection) ? fs.model_class.connection : connection
@ -859,7 +859,7 @@ def after_teardown # :nodoc:
end
included do
class_attribute :fixture_path, :instance_writer => false
class_attribute :fixture_path, instance_writer: false
class_attribute :fixture_table_names
class_attribute :fixture_class_names
class_attribute :use_transactional_tests

@ -11,7 +11,7 @@ module Integration
# Accepts any of the symbols in <tt>Time::DATE_FORMATS</tt>.
#
# This is +:usec+, by default.
class_attribute :cache_timestamp_format, :instance_writer => false
class_attribute :cache_timestamp_format, instance_writer: false
self.cache_timestamp_format = :usec
end

@ -59,7 +59,7 @@ module Pessimistic
# or pass true for "FOR UPDATE" (the default, an exclusive row lock). Returns
# the locked record.
def lock!(lock = true)
reload(:lock => lock) if persisted?
reload(lock: lock) if persisted?
self
end

@ -1242,7 +1242,7 @@ def validate(migrations)
def record_version_state_after_migrating(version)
if down?
migrated.delete(version)
ActiveRecord::SchemaMigration.where(:version => version.to_s).delete_all
ActiveRecord::SchemaMigration.where(version: version.to_s).delete_all
else
migrated << version
ActiveRecord::SchemaMigration.create!(version: version.to_s)

@ -317,7 +317,7 @@ module ClassMethods
# # creates avatar_attributes= and posts_attributes=
# accepts_nested_attributes_for :avatar, :posts, allow_destroy: true
def accepts_nested_attributes_for(*attr_names)
options = { :allow_destroy => false, :update_only => false }
options = { allow_destroy: false, update_only: false }
options.update(attr_names.extract_options!)
options.assert_valid_keys(:allow_destroy, :reject_if, :limit, :update_only)
options[:reject_if] = REJECT_ALL_BLANK_PROC if options[:reject_if] == :all_blank

@ -13,8 +13,8 @@ module ActiveRecord
class Railtie < Rails::Railtie # :nodoc:
config.active_record = ActiveSupport::OrderedOptions.new
config.app_generators.orm :active_record, :migration => true,
:timestamps => true
config.app_generators.orm :active_record, migration: true,
timestamps: true
config.action_dispatch.rescue_responses.merge!(
"ActiveRecord::RecordNotFound" => :not_found,

@ -7,7 +7,7 @@ db_namespace = namespace :db do
ActiveRecord::InternalMetadata[:environment] = ActiveRecord::Migrator.current_environment
end
task :check_protected_environments => [:environment, :load_config] do
task check_protected_environments: [:environment, :load_config] do
ActiveRecord::Tasks::DatabaseTasks.check_protected_environments!
end
@ -17,24 +17,24 @@ db_namespace = namespace :db do
end
namespace :create do
task :all => :load_config do
task all: :load_config do
ActiveRecord::Tasks::DatabaseTasks.create_all
end
end
desc "Creates the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:create:all to create all databases in the config). Without RAILS_ENV or when RAILS_ENV is development, it defaults to creating the development and test databases."
task :create => [:load_config] do
task create: [:load_config] do
ActiveRecord::Tasks::DatabaseTasks.create_current
end
namespace :drop do
task :all => [:load_config, :check_protected_environments] do
task all: [:load_config, :check_protected_environments] do
ActiveRecord::Tasks::DatabaseTasks.drop_all
end
end
desc "Drops the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases in the config). Without RAILS_ENV or when RAILS_ENV is development, it defaults to dropping the development and test databases."
task :drop => [:load_config, :check_protected_environments] do
task drop: [:load_config, :check_protected_environments] do
db_namespace["drop:_unsafe"].invoke
end
@ -43,18 +43,18 @@ db_namespace = namespace :db do
end
namespace :purge do
task :all => [:load_config, :check_protected_environments] do
task all: [:load_config, :check_protected_environments] do
ActiveRecord::Tasks::DatabaseTasks.purge_all
end
end
# desc "Empty the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:purge:all to purge all databases in the config). Without RAILS_ENV it defaults to purging the development and test databases."
task :purge => [:load_config, :check_protected_environments] do
task purge: [:load_config, :check_protected_environments] do
ActiveRecord::Tasks::DatabaseTasks.purge_current
end
desc "Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)."
task :migrate => [:environment, :load_config] do
task migrate: [:environment, :load_config] do
ActiveRecord::Tasks::DatabaseTasks.migrate
db_namespace["_dump"].invoke
end
@ -76,7 +76,7 @@ db_namespace = namespace :db do
namespace :migrate do
# desc 'Rollbacks the database one migration and re migrate up (options: STEP=x, VERSION=x).'
task :redo => [:environment, :load_config] do
task redo: [:environment, :load_config] do
if ENV["VERSION"]
db_namespace["migrate:down"].invoke
db_namespace["migrate:up"].invoke
@ -87,10 +87,10 @@ db_namespace = namespace :db do
end
# desc 'Resets your database using your migrations for the current environment'
task :reset => ["db:drop", "db:create", "db:migrate"]
task reset: ["db:drop", "db:create", "db:migrate"]
# desc 'Runs the "up" for a given migration VERSION.'
task :up => [:environment, :load_config] do
task up: [:environment, :load_config] do
version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil
raise "VERSION is required" unless version
ActiveRecord::Migrator.run(:up, ActiveRecord::Tasks::DatabaseTasks.migrations_paths, version)
@ -98,7 +98,7 @@ db_namespace = namespace :db do
end
# desc 'Runs the "down" for a given migration VERSION.'
task :down => [:environment, :load_config] do
task down: [:environment, :load_config] do
version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil
raise "VERSION is required - To go down one migration, run db:rollback" unless version
ActiveRecord::Migrator.run(:down, ActiveRecord::Tasks::DatabaseTasks.migrations_paths, version)
@ -106,7 +106,7 @@ db_namespace = namespace :db do
end
desc "Display status of migrations"
task :status => [:environment, :load_config] do
task status: [:environment, :load_config] do
unless ActiveRecord::SchemaMigration.table_exists?
abort "Schema migrations table does not exist yet."
end
@ -139,29 +139,29 @@ db_namespace = namespace :db do
end
desc "Rolls the schema back to the previous version (specify steps w/ STEP=n)."
task :rollback => [:environment, :load_config] do
task rollback: [:environment, :load_config] do
step = ENV["STEP"] ? ENV["STEP"].to_i : 1
ActiveRecord::Migrator.rollback(ActiveRecord::Tasks::DatabaseTasks.migrations_paths, step)
db_namespace["_dump"].invoke
end
# desc 'Pushes the schema to the next version (specify steps w/ STEP=n).'
task :forward => [:environment, :load_config] do
task forward: [:environment, :load_config] do
step = ENV["STEP"] ? ENV["STEP"].to_i : 1
ActiveRecord::Migrator.forward(ActiveRecord::Tasks::DatabaseTasks.migrations_paths, step)
db_namespace["_dump"].invoke
end
# desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.'
task :reset => [ "db:drop", "db:setup" ]
task reset: [ "db:drop", "db:setup" ]
# desc "Retrieves the charset for the current environment's database"
task :charset => [:environment, :load_config] do
task charset: [:environment, :load_config] do
puts ActiveRecord::Tasks::DatabaseTasks.charset_current
end
# desc "Retrieves the collation for the current environment's database"
task :collation => [:environment, :load_config] do
task collation: [:environment, :load_config] do
begin
puts ActiveRecord::Tasks::DatabaseTasks.collation_current
rescue NoMethodError
@ -170,12 +170,12 @@ db_namespace = namespace :db do
end
desc "Retrieves the current schema version number"
task :version => [:environment, :load_config] do
task version: [:environment, :load_config] do
puts "Current version: #{ActiveRecord::Migrator.current_version}"
end
# desc "Raises an error if there are pending migrations"
task :abort_if_pending_migrations => [:environment, :load_config] do
task abort_if_pending_migrations: [:environment, :load_config] do
pending_migrations = ActiveRecord::Migrator.open(ActiveRecord::Tasks::DatabaseTasks.migrations_paths).pending_migrations
if pending_migrations.any?
@ -188,7 +188,7 @@ db_namespace = namespace :db do
end
desc "Creates the database, loads the schema, and initializes with the seed data (use db:reset to also drop the database first)"
task :setup => ["db:schema:load_if_ruby", "db:structure:load_if_sql", :seed]
task setup: ["db:schema:load_if_ruby", "db:structure:load_if_sql", :seed]
desc "Loads the seed data from db/seeds.rb"
task :seed do
@ -198,7 +198,7 @@ db_namespace = namespace :db do
namespace :fixtures do
desc "Loads fixtures into the current environment's database. Load specific fixtures using FIXTURES=x,y. Load from subdirectory in test/fixtures using FIXTURES_DIR=z. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures."
task :load => [:environment, :load_config] do
task load: [:environment, :load_config] do
require "active_record/fixtures"
base_dir = ActiveRecord::Tasks::DatabaseTasks.fixtures_path
@ -220,7 +220,7 @@ db_namespace = namespace :db do
end
# desc "Search for a fixture given a LABEL or ID. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures."
task :identify => [:environment, :load_config] do
task identify: [:environment, :load_config] do
require "active_record/fixtures"
label, id = ENV["LABEL"], ENV["ID"]
@ -246,7 +246,7 @@ db_namespace = namespace :db do
namespace :schema do
desc "Creates a db/schema.rb file that is portable against any DB supported by Active Record"
task :dump => [:environment, :load_config] do
task dump: [:environment, :load_config] do
require "active_record/schema_dumper"
filename = ENV["SCHEMA"] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema.rb")
File.open(filename, "w:utf-8") do |file|
@ -256,17 +256,17 @@ db_namespace = namespace :db do
end
desc "Loads a schema.rb file into the database"
task :load => [:environment, :load_config, :check_protected_environments] do
task load: [:environment, :load_config, :check_protected_environments] do
ActiveRecord::Tasks::DatabaseTasks.load_schema_current(:ruby, ENV["SCHEMA"])
end
task :load_if_ruby => ["db:create", :environment] do
task load_if_ruby: ["db:create", :environment] do
db_namespace["schema:load"].invoke if ActiveRecord::Base.schema_format == :ruby
end
namespace :cache do
desc "Creates a db/schema_cache.dump file."
task :dump => [:environment, :load_config] do
task dump: [:environment, :load_config] do
con = ActiveRecord::Base.connection
filename = File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema_cache.dump")
@ -276,7 +276,7 @@ db_namespace = namespace :db do
end
desc "Clears a db/schema_cache.dump file."
task :clear => [:environment, :load_config] do
task clear: [:environment, :load_config] do
filename = File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema_cache.dump")
rm_f filename, verbose: false
end
@ -286,7 +286,7 @@ db_namespace = namespace :db do
namespace :structure do
desc "Dumps the database structure to db/structure.sql. Specify another file with SCHEMA=db/my_structure.sql"
task :dump => [:environment, :load_config] do
task dump: [:environment, :load_config] do
filename = ENV["SCHEMA"] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "structure.sql")
current_config = ActiveRecord::Tasks::DatabaseTasks.current_config
ActiveRecord::Tasks::DatabaseTasks.structure_dump(current_config, filename)
@ -302,11 +302,11 @@ db_namespace = namespace :db do
end
desc "Recreates the databases from the structure.sql file"
task :load => [:environment, :load_config, :check_protected_environments] do
task load: [:environment, :load_config, :check_protected_environments] do
ActiveRecord::Tasks::DatabaseTasks.load_schema_current(:sql, ENV["SCHEMA"])
end
task :load_if_sql => ["db:create", :environment] do
task load_if_sql: ["db:create", :environment] do
db_namespace["structure:load"].invoke if ActiveRecord::Base.schema_format == :sql
end
end
@ -321,7 +321,7 @@ db_namespace = namespace :db do
end
# desc "Recreate the test database from the current schema"
task :load => %w(db:test:purge) do
task load: %w(db:test:purge) do
case ActiveRecord::Base.schema_format
when :ruby
db_namespace["test:load_schema"].invoke
@ -331,7 +331,7 @@ db_namespace = namespace :db do
end
# desc "Recreate the test database from an existent schema.rb file"
task :load_schema => %w(db:test:purge) do
task load_schema: %w(db:test:purge) do
begin
should_reconnect = ActiveRecord::Base.connection_pool.active_connection?
ActiveRecord::Schema.verbose = false
@ -344,12 +344,12 @@ db_namespace = namespace :db do
end
# desc "Recreate the test database from an existent structure.sql file"
task :load_structure => %w(db:test:purge) do
task load_structure: %w(db:test:purge) do
ActiveRecord::Tasks::DatabaseTasks.load_schema ActiveRecord::Base.configurations["test"], :sql, ENV["SCHEMA"]
end
# desc "Recreate the test database from a fresh schema"
task :clone => %w(db:test:deprecated environment) do
task clone: %w(db:test:deprecated environment) do
case ActiveRecord::Base.schema_format
when :ruby
db_namespace["test:clone_schema"].invoke
@ -359,18 +359,18 @@ db_namespace = namespace :db do
end
# desc "Recreate the test database from a fresh schema.rb file"
task :clone_schema => %w(db:test:deprecated db:schema:dump db:test:load_schema)
task clone_schema: %w(db:test:deprecated db:schema:dump db:test:load_schema)
# desc "Recreate the test database from a fresh structure.sql file"
task :clone_structure => %w(db:test:deprecated db:structure:dump db:test:load_structure)
task clone_structure: %w(db:test:deprecated db:structure:dump db:test:load_structure)
# desc "Empty the test database"
task :purge => %w(environment load_config check_protected_environments) do
task purge: %w(environment load_config check_protected_environments) do
ActiveRecord::Tasks::DatabaseTasks.purge ActiveRecord::Base.configurations["test"]
end
# desc 'Load the test schema'
task :prepare => %w(environment load_config) do
task prepare: %w(environment load_config) do
unless ActiveRecord::Base.configurations.blank?
db_namespace["test:load"].invoke
end
@ -381,7 +381,7 @@ end
namespace :railties do
namespace :install do
# desc "Copies missing migrations from Railties (e.g. engines). You can specify Railties to use with FROM=railtie1,railtie2"
task :migrations => :'db:load_config' do
task migrations: :'db:load_config' do
to_load = ENV["FROM"].blank? ? :all : ENV["FROM"].split(",").map(&:strip)
railties = {}
Rails.application.migration_railties.each do |railtie|
@ -401,7 +401,7 @@ namespace :railties do
end
ActiveRecord::Migration.copy(ActiveRecord::Tasks::DatabaseTasks.migrations_paths.first, railties,
:on_skip => on_skip, :on_copy => on_copy)
on_skip: on_skip, on_copy: on_copy)
end
end
end

@ -700,7 +700,7 @@ def collection?
class ThroughReflection < AbstractReflection #:nodoc:
attr_reader :delegate_reflection
delegate :foreign_key, :foreign_type, :association_foreign_key,
:active_record_primary_key, :type, :to => :source_reflection
:active_record_primary_key, :type, to: :source_reflection
def initialize(delegate_reflection)
@delegate_reflection = delegate_reflection

@ -41,7 +41,7 @@ def inherited(child_class)
:shuffle, :split, to: :records
delegate :table_name, :quoted_table_name, :primary_key, :quoted_primary_key,
:connection, :columns_hash, :to => :klass
:connection, :columns_hash, to: :klass
module ClassSpecificRelation # :nodoc:
extend ActiveSupport::Concern
@ -88,7 +88,7 @@ def method_missing(method, *args, &block)
self.class.delegate_to_scoped_klass(method)
scoping { @klass.public_send(method, *args, &block) }
elsif arel.respond_to?(method)
self.class.delegate method, :to => :arel
self.class.delegate method, to: :arel
arel.public_send(method, *args, &block)
else
super

@ -96,7 +96,7 @@ def seed_loader
end
def current_config(options = {})
options.reverse_merge! :env => env
options.reverse_merge! env: env
if options.has_key?(:config)
@current_config = options[:config]
else

@ -4,7 +4,7 @@
module ActiveRecord
module Generators # :nodoc:
class MigrationGenerator < Base # :nodoc:
argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]"
argument :attributes, type: :array, default: [], banner: "field[:type][:index] field[:type][:index]"
class_option :primary_key_type, type: :string, desc: "The type for primary key"

@ -3,7 +3,7 @@
module ActiveRecord
module Generators # :nodoc:
class ModelGenerator < Base # :nodoc:
argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]"
argument :attributes, type: :array, default: [], banner: "field[:type][:index] field[:type][:index]"
check_class_collision

@ -73,7 +73,7 @@ def test_indexes
indexes = @connection.indexes("accounts")
assert indexes.empty?
@connection.add_index :accounts, :firm_id, :name => idx_name
@connection.add_index :accounts, :firm_id, name: idx_name
indexes = @connection.indexes("accounts")
assert_equal "accounts", indexes.first.table
assert_equal idx_name, indexes.first.name
@ -84,18 +84,18 @@ def test_indexes
end
ensure
@connection.remove_index(:accounts, :name => idx_name) rescue nil
@connection.remove_index(:accounts, name: idx_name) rescue nil
end
def test_remove_index_when_name_and_wrong_column_name_specified
index_name = "accounts_idx"
@connection.add_index :accounts, :firm_id, :name => index_name
@connection.add_index :accounts, :firm_id, name: index_name
assert_raises ArgumentError do
@connection.remove_index :accounts, :name => index_name, :column => :wrong_column_name
@connection.remove_index :accounts, name: index_name, column: :wrong_column_name
end
ensure
@connection.remove_index(:accounts, :name => index_name)
@connection.remove_index(:accounts, name: index_name)
end
def test_current_database
@ -163,13 +163,13 @@ class << @connection
def test_reset_empty_table_with_custom_pk
Movie.delete_all
Movie.connection.reset_pk_sequence! "movies"
assert_equal 1, Movie.create(:name => "fight club").id
assert_equal 1, Movie.create(name: "fight club").id
end
def test_reset_table_with_non_integer_pk
Subscriber.delete_all
Subscriber.connection.reset_pk_sequence! "subscribers"
sub = Subscriber.new(:name => "robert drake")
sub = Subscriber.new(name: "robert drake")
sub.id = "bob drake"
assert_nothing_raised { sub.save! }
end

@ -21,42 +21,42 @@ def (ActiveRecord::Base.connection).data_source_exists?(*); true; end
def (ActiveRecord::Base.connection).index_name_exists?(*); false; end
expected = "CREATE INDEX `index_people_on_last_name` ON `people` (`last_name`) "
assert_equal expected, add_index(:people, :last_name, :length => nil)
assert_equal expected, add_index(:people, :last_name, length: nil)
expected = "CREATE INDEX `index_people_on_last_name` ON `people` (`last_name`(10)) "
assert_equal expected, add_index(:people, :last_name, :length => 10)
assert_equal expected, add_index(:people, :last_name, length: 10)
expected = "CREATE INDEX `index_people_on_last_name_and_first_name` ON `people` (`last_name`(15), `first_name`(15)) "
assert_equal expected, add_index(:people, [:last_name, :first_name], :length => 15)
assert_equal expected, add_index(:people, [:last_name, :first_name], length: 15)
expected = "CREATE INDEX `index_people_on_last_name_and_first_name` ON `people` (`last_name`(15), `first_name`) "
assert_equal expected, add_index(:people, [:last_name, :first_name], :length => {:last_name => 15})
assert_equal expected, add_index(:people, [:last_name, :first_name], length: {last_name: 15})
expected = "CREATE INDEX `index_people_on_last_name_and_first_name` ON `people` (`last_name`(15), `first_name`(10)) "
assert_equal expected, add_index(:people, [:last_name, :first_name], :length => {:last_name => 15, :first_name => 10})
assert_equal expected, add_index(:people, [:last_name, :first_name], length: {last_name: 15, first_name: 10})
%w(SPATIAL FULLTEXT UNIQUE).each do |type|
expected = "CREATE #{type} INDEX `index_people_on_last_name` ON `people` (`last_name`) "
assert_equal expected, add_index(:people, :last_name, :type => type)
assert_equal expected, add_index(:people, :last_name, type: type)
end
%w(btree hash).each do |using|
expected = "CREATE INDEX `index_people_on_last_name` USING #{using} ON `people` (`last_name`) "
assert_equal expected, add_index(:people, :last_name, :using => using)
assert_equal expected, add_index(:people, :last_name, using: using)
end
expected = "CREATE INDEX `index_people_on_last_name` USING btree ON `people` (`last_name`(10)) "
assert_equal expected, add_index(:people, :last_name, :length => 10, :using => :btree)
assert_equal expected, add_index(:people, :last_name, length: 10, using: :btree)
expected = "CREATE INDEX `index_people_on_last_name` USING btree ON `people` (`last_name`(10)) ALGORITHM = COPY"
assert_equal expected, add_index(:people, :last_name, :length => 10, using: :btree, algorithm: :copy)
assert_equal expected, add_index(:people, :last_name, length: 10, using: :btree, algorithm: :copy)
assert_raise ArgumentError do
add_index(:people, :last_name, algorithm: :coyp)
end
expected = "CREATE INDEX `index_people_on_last_name_and_first_name` USING btree ON `people` (`last_name`(15), `first_name`(15)) "
assert_equal expected, add_index(:people, [:last_name, :first_name], :length => 15, :using => :btree)
assert_equal expected, add_index(:people, [:last_name, :first_name], length: 15, using: :btree)
end
def test_index_in_create
@ -102,13 +102,13 @@ def test_drop_table
def test_create_mysql_database_with_encoding
assert_equal "CREATE DATABASE `matt` DEFAULT CHARACTER SET `utf8`", create_database(:matt)
assert_equal "CREATE DATABASE `aimonetti` DEFAULT CHARACTER SET `latin1`", create_database(:aimonetti, {:charset => "latin1"})
assert_equal "CREATE DATABASE `matt_aimonetti` DEFAULT CHARACTER SET `big5` COLLATE `big5_chinese_ci`", create_database(:matt_aimonetti, {:charset => :big5, :collation => :big5_chinese_ci})
assert_equal "CREATE DATABASE `aimonetti` DEFAULT CHARACTER SET `latin1`", create_database(:aimonetti, {charset: "latin1"})
assert_equal "CREATE DATABASE `matt_aimonetti` DEFAULT CHARACTER SET `big5` COLLATE `big5_chinese_ci`", create_database(:matt_aimonetti, {charset: :big5, collation: :big5_chinese_ci})
end
def test_recreate_mysql_database_with_encoding
create_database(:luca, {:charset => "latin1"})
assert_equal "CREATE DATABASE `luca` DEFAULT CHARACTER SET `latin1`", recreate_database(:luca, {:charset => "latin1"})
create_database(:luca, {charset: "latin1"})
assert_equal "CREATE DATABASE `luca` DEFAULT CHARACTER SET `latin1`", recreate_database(:luca, {charset: "latin1"})
end
def test_add_column
@ -116,7 +116,7 @@ def test_add_column
end
def test_add_column_with_limit
assert_equal "ALTER TABLE `people` ADD `key` varchar(32)", add_column(:people, :key, :string, :limit => 32)
assert_equal "ALTER TABLE `people` ADD `key` varchar(32)", add_column(:people, :key, :string, limit: 32)
end
def test_drop_table_with_specific_database

@ -20,7 +20,7 @@ def test_update_question_marks
def test_create_question_marks
str = "foo?bar"
x = Topic.create!(:title => str, :content => str)
x = Topic.create!(title: str, content: str)
x.reload
assert_equal str, x.title
assert_equal str, x.content
@ -39,7 +39,7 @@ def test_update_null_bytes
def test_create_null_bytes
str = "foo\0bar"
x = Topic.create!(:title => str, :content => str)
x = Topic.create!(title: str, content: str)
x.reload
assert_equal str, x.title
assert_equal str, x.content

@ -17,36 +17,36 @@ def test_case_sensitive
end
def test_case_insensitive_comparison_for_ci_column
CollationTest.validates_uniqueness_of(:string_ci_column, :case_sensitive => false)
CollationTest.create!(:string_ci_column => "A")
invalid = CollationTest.new(:string_ci_column => "a")
CollationTest.validates_uniqueness_of(:string_ci_column, case_sensitive: false)
CollationTest.create!(string_ci_column: "A")
invalid = CollationTest.new(string_ci_column: "a")
queries = assert_sql { invalid.save }
ci_uniqueness_query = queries.detect { |q| q.match(/string_ci_column/) }
assert_no_match(/lower/i, ci_uniqueness_query)
end
def test_case_insensitive_comparison_for_cs_column
CollationTest.validates_uniqueness_of(:string_cs_column, :case_sensitive => false)
CollationTest.create!(:string_cs_column => "A")
invalid = CollationTest.new(:string_cs_column => "a")
CollationTest.validates_uniqueness_of(:string_cs_column, case_sensitive: false)
CollationTest.create!(string_cs_column: "A")
invalid = CollationTest.new(string_cs_column: "a")
queries = assert_sql { invalid.save }
cs_uniqueness_query = queries.detect { |q| q.match(/string_cs_column/)}
assert_match(/lower/i, cs_uniqueness_query)
end
def test_case_sensitive_comparison_for_ci_column
CollationTest.validates_uniqueness_of(:string_ci_column, :case_sensitive => true)
CollationTest.create!(:string_ci_column => "A")
invalid = CollationTest.new(:string_ci_column => "A")
CollationTest.validates_uniqueness_of(:string_ci_column, case_sensitive: true)
CollationTest.create!(string_ci_column: "A")
invalid = CollationTest.new(string_ci_column: "A")
queries = assert_sql { invalid.save }
ci_uniqueness_query = queries.detect { |q| q.match(/string_ci_column/) }
assert_match(/binary/i, ci_uniqueness_query)
end
def test_case_sensitive_comparison_for_cs_column
CollationTest.validates_uniqueness_of(:string_cs_column, :case_sensitive => true)
CollationTest.create!(:string_cs_column => "A")
invalid = CollationTest.new(:string_cs_column => "A")
CollationTest.validates_uniqueness_of(:string_cs_column, case_sensitive: true)
CollationTest.create!(string_cs_column: "A")
invalid = CollationTest.new(string_cs_column: "A")
queries = assert_sql { invalid.save }
cs_uniqueness_query = queries.detect { |q| q.match(/string_cs_column/) }
assert_no_match(/binary/i, cs_uniqueness_query)

@ -114,7 +114,7 @@ def test_passing_flags_by_array_to_adapter
def test_mysql_set_session_variable
run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:default_week_format => 3}}))
ActiveRecord::Base.establish_connection(orig_connection.deep_merge({variables: {default_week_format: 3}}))
session_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT"
assert_equal 3, session_mode.rows.first.first.to_i
end
@ -122,7 +122,7 @@ def test_mysql_set_session_variable
def test_mysql_set_session_variable_to_default
run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:default_week_format => :default}}))
ActiveRecord::Base.establish_connection(orig_connection.deep_merge({variables: {default_week_format: :default}}))
global_mode = ActiveRecord::Base.connection.exec_query "SELECT @@GLOBAL.DEFAULT_WEEK_FORMAT"
session_mode = ActiveRecord::Base.connection.exec_query "SELECT @@SESSION.DEFAULT_WEEK_FORMAT"
assert_equal global_mode.rows, session_mode.rows

@ -21,7 +21,7 @@ class Values < ActiveRecord::Base
class Distinct < ActiveRecord::Base
Distinct.table_name = "distinct"
has_and_belongs_to_many :selects
has_many :values, :through => :groups
has_many :values, through: :groups
end
def setup
@ -59,7 +59,7 @@ def test_rename_tables
def test_change_columns
assert_nothing_raised { @connection.change_column_default(:group, :order, "whatever") }
#the quoting here will reveal any double quoting issues in change_column's interaction with the column method in the adapter
assert_nothing_raised { @connection.change_column("group", "order", :Int, :default => 0) }
assert_nothing_raised { @connection.change_column("group", "order", :Int, default: 0) }
assert_nothing_raised { @connection.rename_column(:group, :order, :values) }
end
@ -124,7 +124,7 @@ def test_calculations_work_with_reserved_words
end
def test_associations_work_with_reserved_words
assert_nothing_raised { Select.all.merge!(:includes => [:groups]).to_a }
assert_nothing_raised { Select.all.merge!(includes: [:groups]).to_a }
end
#the following functions were added to DRY test cases

@ -15,12 +15,12 @@ def execute(sql, name = nil) sql end
def test_create_database_with_encoding
assert_equal %(CREATE DATABASE "matt" ENCODING = 'utf8'), create_database(:matt)
assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'latin1'), create_database(:aimonetti, :encoding => :latin1)
assert_equal %(CREATE DATABASE "aimonetti" ENCODING = 'latin1'), create_database(:aimonetti, encoding: :latin1)
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")
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

@ -10,7 +10,7 @@ class PostgresqlBitString < ActiveRecord::Base; end
def setup
@connection = ActiveRecord::Base.connection
@connection.create_table("postgresql_bit_strings", :force => true) do |t|
@connection.create_table("postgresql_bit_strings", force: true) do |t|
t.bit :a_bit, default: "00000011", limit: 8
t.bit_varying :a_bit_varying, default: "0011", limit: 4
t.bit :another_bit

@ -184,7 +184,7 @@ def test_reconnection_after_actual_disconnection_with_verify
def test_set_session_variable_true
run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:debug_print_plan => true}}))
ActiveRecord::Base.establish_connection(orig_connection.deep_merge({variables: {debug_print_plan: true}}))
set_true = ActiveRecord::Base.connection.exec_query "SHOW DEBUG_PRINT_PLAN"
assert_equal set_true.rows, [["on"]]
end
@ -192,7 +192,7 @@ def test_set_session_variable_true
def test_set_session_variable_false
run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:debug_print_plan => false}}))
ActiveRecord::Base.establish_connection(orig_connection.deep_merge({variables: {debug_print_plan: false}}))
set_false = ActiveRecord::Base.connection.exec_query "SHOW DEBUG_PRINT_PLAN"
assert_equal set_false.rows, [["off"]]
end
@ -201,14 +201,14 @@ def test_set_session_variable_false
def test_set_session_variable_nil
run_without_connection do |orig_connection|
# This should be a no-op that does not raise an error
ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:debug_print_plan => nil}}))
ActiveRecord::Base.establish_connection(orig_connection.deep_merge({variables: {debug_print_plan: nil}}))
end
end
def test_set_session_variable_default
run_without_connection do |orig_connection|
# This should execute a query that does not raise an error
ActiveRecord::Base.establish_connection(orig_connection.deep_merge({:variables => {:debug_print_plan => :default}}))
ActiveRecord::Base.establish_connection(orig_connection.deep_merge({variables: {debug_print_plan: :default}}))
end
end

@ -195,11 +195,11 @@ class PostgresqlGeometric < ActiveRecord::Base; end
def test_geometric_types
g = PostgresqlGeometric.new(
:a_line_segment => "(2.0, 3), (5.5, 7.0)",
:a_box => "2.0, 3, 5.5, 7.0",
:a_path => "[(2.0, 3), (5.5, 7.0), (8.5, 11.0)]",
:a_polygon => "((2.0, 3), (5.5, 7.0), (8.5, 11.0))",
:a_circle => "<(5.3, 10.4), 2>"
a_line_segment: "(2.0, 3), (5.5, 7.0)",
a_box: "2.0, 3, 5.5, 7.0",
a_path: "[(2.0, 3), (5.5, 7.0), (8.5, 11.0)]",
a_polygon: "((2.0, 3), (5.5, 7.0), (8.5, 11.0))",
a_circle: "<(5.3, 10.4), 2>"
)
g.save!
@ -215,11 +215,11 @@ def test_geometric_types
def test_alternative_format
g = PostgresqlGeometric.new(
:a_line_segment => "((2.0, 3), (5.5, 7.0))",
:a_box => "(2.0, 3), (5.5, 7.0)",
:a_path => "((2.0, 3), (5.5, 7.0), (8.5, 11.0))",
:a_polygon => "2.0, 3, 5.5, 7.0, 8.5, 11.0",
:a_circle => "((5.3, 10.4), 2)"
a_line_segment: "((2.0, 3), (5.5, 7.0))",
a_box: "(2.0, 3), (5.5, 7.0)",
a_path: "((2.0, 3), (5.5, 7.0), (8.5, 11.0))",
a_polygon: "2.0, 3, 5.5, 7.0, 8.5, 11.0",
a_circle: "((5.3, 10.4), 2)"
)
g.save!

@ -22,7 +22,7 @@ def setup
@connection.transaction do
@connection.create_table("hstores") do |t|
t.hstore "tags", :default => ""
t.hstore "tags", default: ""
t.hstore "payload", array: true
t.hstore "settings"
end
@ -338,12 +338,12 @@ def assert_array_cycle(array)
def assert_cycle(hash)
# test creation
x = Hstore.create!(:tags => hash)
x = Hstore.create!(tags: hash)
x.reload
assert_equal(hash, x.tags)
# test updating
x = Hstore.create!(:tags => {})
x = Hstore.create!(tags: {})
x.tags = hash
x.save!
x.reload

@ -253,7 +253,7 @@ def test_exec_typecasts_bind_vals
def test_partial_index
with_example_table do
@connection.add_index "ex", %w{ id number }, :name => "partial", :where => "number > 100"
@connection.add_index "ex", %w{ id number }, name: "partial", where: "number > 100"
index = @connection.indexes("ex").find { |idx| idx.name == "partial" }
assert_equal "(number > 100)", index.where
end
@ -395,7 +395,7 @@ def with_example_table(definition = "id serial primary key, number integer, data
end
def connection_without_insert_returning
ActiveRecord::Base.postgresql_connection(ActiveRecord::Base.configurations["arunit"].merge(:insert_returning => false))
ActiveRecord::Base.postgresql_connection(ActiveRecord::Base.configurations["arunit"].merge(insert_returning: false))
end
end
end

@ -90,9 +90,9 @@ def test_sequence_schema_caching
assert_nothing_raised do
USERS.each do |u|
set_session_auth u
st = SchemaThing.new :name => "TEST1"
st = SchemaThing.new name: "TEST1"
st.save!
st = SchemaThing.new :id => 5, :name => "TEST2"
st = SchemaThing.new id: 5, name: "TEST2"
st.save!
set_session_auth
end

@ -260,25 +260,25 @@ def test_classes_with_qualified_schema_name
assert_equal 0, Thing3.count
assert_equal 0, Thing4.count
Thing1.create(:id => 1, :name => "thing1", :email => "thing1@localhost", :moment => Time.now)
Thing1.create(id: 1, name: "thing1", email: "thing1@localhost", moment: Time.now)
assert_equal 1, Thing1.count
assert_equal 0, Thing2.count
assert_equal 0, Thing3.count
assert_equal 0, Thing4.count
Thing2.create(:id => 1, :name => "thing1", :email => "thing1@localhost", :moment => Time.now)
Thing2.create(id: 1, name: "thing1", email: "thing1@localhost", moment: Time.now)
assert_equal 1, Thing1.count
assert_equal 1, Thing2.count
assert_equal 0, Thing3.count
assert_equal 0, Thing4.count
Thing3.create(:id => 1, :name => "thing1", :email => "thing1@localhost", :moment => Time.now)
Thing3.create(id: 1, name: "thing1", email: "thing1@localhost", moment: Time.now)
assert_equal 1, Thing1.count
assert_equal 1, Thing2.count
assert_equal 1, Thing3.count
assert_equal 0, Thing4.count
Thing4.create(:id => 1, :name => "thing1", :email => "thing1@localhost", :moment => Time.now)
Thing4.create(id: 1, name: "thing1", email: "thing1@localhost", moment: Time.now)
assert_equal 1, Thing1.count
assert_equal 1, Thing2.count
assert_equal 1, Thing3.count
@ -401,7 +401,7 @@ def test_current_schema
def test_prepared_statements_with_multiple_schemas
[SCHEMA_NAME, SCHEMA2_NAME].each do |schema_name|
with_schema_search_path schema_name do
Thing5.create(:id => 1, :name => "thing inside #{SCHEMA_NAME}", :email => "thing1@localhost", :moment => Time.now)
Thing5.create(id: 1, name: "thing inside #{SCHEMA_NAME}", email: "thing1@localhost", moment: Time.now)
end
end

@ -63,28 +63,28 @@ def test_load_infinity_and_beyond
end
def test_save_infinity_and_beyond
d = Developer.create!(:name => "aaron", :updated_at => 1.0 / 0.0)
d = Developer.create!(name: "aaron", updated_at: 1.0 / 0.0)
assert_equal(1.0 / 0.0, d.updated_at)
d = Developer.create!(:name => "aaron", :updated_at => -1.0 / 0.0)
d = Developer.create!(name: "aaron", updated_at: -1.0 / 0.0)
assert_equal(-1.0 / 0.0, d.updated_at)
end
def test_bc_timestamp
date = Date.new(0) - 1.week
Developer.create!(:name => "aaron", :updated_at => date)
Developer.create!(name: "aaron", updated_at: date)
assert_equal date, Developer.find_by_name("aaron").updated_at
end
def test_bc_timestamp_leap_year
date = Time.utc(-4, 2, 29)
Developer.create!(:name => "taihou", :updated_at => date)
Developer.create!(name: "taihou", updated_at: date)
assert_equal date, Developer.find_by_name("taihou").updated_at
end
def test_bc_timestamp_year_zero
date = Time.utc(0, 4, 7)
Developer.create!(:name => "yahagi", :updated_at => date)
Developer.create!(name: "yahagi", updated_at: date)
assert_equal date, Developer.find_by_name("yahagi").updated_at
end
end

@ -25,7 +25,7 @@ def test_copy_table(from = "customers", to = "customers2", options = {})
def test_copy_table_renaming_column
test_copy_table("customers", "customers2",
:rename => {"name" => "person_name"}) do |from, to, options|
rename: {"name" => "person_name"}) do |from, to, options|
expected = column_values(from, "name")
assert_equal expected, column_values(to, "person_name")
assert expected.any?, "No values in table: #{expected.inspect}"
@ -77,7 +77,7 @@ def test_copy_table_with_binary_column
protected
def copy_table(from, to, options = {})
@connection.copy_table(from, to, {:temporary => true}.merge(options))
@connection.copy_table(from, to, {temporary: true}.merge(options))
end
def column_names(table)

@ -8,9 +8,9 @@ def test_sqlite_creates_directory
Dir.mktmpdir do |dir|
begin
dir = Pathname.new(dir)
@conn = Base.sqlite3_connection :database => dir.join("db/foo.sqlite3"),
:adapter => "sqlite3",
:timeout => 100
@conn = Base.sqlite3_connection database: dir.join("db/foo.sqlite3"),
adapter: "sqlite3",
timeout: 100
assert Dir.exist? dir.join("db")
assert File.exist? dir.join("db/foo.sqlite3")

@ -154,11 +154,11 @@ class OverridingAggregationsTest < ActiveRecord::TestCase
class DifferentName; end
class Person < ActiveRecord::Base
composed_of :composed_of, :mapping => %w(person_first_name first_name)
composed_of :composed_of, mapping: %w(person_first_name first_name)
end
class DifferentPerson < Person
composed_of :composed_of, :class_name => "DifferentName", :mapping => %w(different_person_first_name first_name)
composed_of :composed_of, class_name: "DifferentName", mapping: %w(different_person_first_name first_name)
end
def test_composed_of_aggregation_redefinition_reflections_should_differ_and_not_inherited

@ -36,7 +36,7 @@ def test_has_primary_key
end
def test_schema_define
ActiveRecord::Schema.define(:version => 7) do
ActiveRecord::Schema.define(version: 7) do
create_table :fruits do |t|
t.column :color, :string
t.column :fruit_size, :string # NOTE: "size" is reserved in Oracle
@ -55,7 +55,7 @@ def test_schema_define_w_table_name_prefix
old_table_name_prefix = ActiveRecord::Base.table_name_prefix
ActiveRecord::Base.table_name_prefix = "nep_"
ActiveRecord::SchemaMigration.table_name = "nep_#{table_name}"
ActiveRecord::Schema.define(:version => 7) do
ActiveRecord::Schema.define(version: 7) do
create_table :fruits do |t|
t.column :color, :string
t.column :fruit_size, :string # NOTE: "size" is reserved in Oracle
@ -71,7 +71,7 @@ def test_schema_define_w_table_name_prefix
def test_schema_raises_an_error_for_invalid_column_type
assert_raise NoMethodError do
ActiveRecord::Schema.define(:version => 8) do
ActiveRecord::Schema.define(version: 8) do
create_table :vegetables do |t|
t.unknown :color
end
@ -80,7 +80,7 @@ def test_schema_raises_an_error_for_invalid_column_type
end
def test_schema_subclass
Class.new(ActiveRecord::Schema).define(:version => 9) do
Class.new(ActiveRecord::Schema).define(version: 9) do
create_table :fruits
end
assert_nothing_raised { @connection.select_all "SELECT * FROM fruits" }

@ -47,7 +47,7 @@ def test_belongs_to_does_not_use_order_by
end
def test_belongs_to_with_primary_key
client = Client.create(:name => "Primary key client", :firm_name => companies(:first_firm).name)
client = Client.create(name: "Primary key client", firm_name: companies(:first_firm).name)
assert_equal companies(:first_firm).name, client.firm_with_primary_key.name
end
@ -129,12 +129,12 @@ def test_default_scope_on_relations_is_not_cached
default_scope -> {
counter += 1
where("id = :inc", :inc => counter)
where("id = :inc", inc: counter)
}
has_many :comments, :anonymous_class => comments
has_many :comments, anonymous_class: comments
}
belongs_to :post, :anonymous_class => posts, :inverse_of => false
belongs_to :post, anonymous_class: posts, inverse_of: false
}
assert_equal 0, counter
@ -203,14 +203,14 @@ def test_natural_assignment_with_primary_key
def test_eager_loading_with_primary_key
Firm.create("name" => "Apple")
Client.create("name" => "Citibank", :firm_name => "Apple")
citibank_result = Client.all.merge!(: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(:firm_with_primary_key).loaded?
end
def test_eager_loading_with_primary_key_as_symbol
Firm.create("name" => "Apple")
Client.create("name" => "Citibank", :firm_name => "Apple")
citibank_result = Client.all.merge!(: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(:firm_with_primary_key_symbols).loaded?
end
@ -224,7 +224,7 @@ def test_creating_the_belonging_object
end
def test_creating_the_belonging_object_with_primary_key
client = Client.create(:name => "Primary key client")
client = Client.create(name: "Primary key client")
apple = client.create_firm_with_primary_key("name" => "Apple")
assert_equal apple, client.firm_with_primary_key
client.save
@ -247,36 +247,36 @@ def test_building_the_belonging_object_with_implicit_sti_base_class
def test_building_the_belonging_object_with_explicit_sti_base_class
account = Account.new
company = account.build_firm(:type => "Company")
company = account.build_firm(type: "Company")
assert_kind_of Company, company, "Expected #{company.class} to be a Company"
end
def test_building_the_belonging_object_with_sti_subclass
account = Account.new
company = account.build_firm(:type => "Firm")
company = account.build_firm(type: "Firm")
assert_kind_of Firm, company, "Expected #{company.class} to be a Firm"
end
def test_building_the_belonging_object_with_an_invalid_type
account = Account.new
assert_raise(ActiveRecord::SubclassNotFound) { account.build_firm(:type => "InvalidType") }
assert_raise(ActiveRecord::SubclassNotFound) { account.build_firm(type: "InvalidType") }
end
def test_building_the_belonging_object_with_an_unrelated_type
account = Account.new
assert_raise(ActiveRecord::SubclassNotFound) { account.build_firm(:type => "Account") }
assert_raise(ActiveRecord::SubclassNotFound) { account.build_firm(type: "Account") }
end
def test_building_the_belonging_object_with_primary_key
client = Client.create(:name => "Primary key client")
client = Client.create(name: "Primary key client")
apple = client.build_firm_with_primary_key("name" => "Apple")
client.save
assert_equal apple.name, client.firm_name
end
def test_create!
client = Client.create!(:name => "Jimmy")
account = client.create_account!(:credit_limit => 10)
client = Client.create!(name: "Jimmy")
account = client.create_account!(credit_limit: 10)
assert_equal account, client.account
assert account.persisted?
client.save
@ -285,7 +285,7 @@ def test_create!
end
def test_failing_create!
client = Client.create!(:name => "Jimmy")
client = Client.create!(name: "Jimmy")
assert_raise(ActiveRecord::RecordInvalid) { client.create_account! }
assert_not_nil client.account
assert client.account.new_record?
@ -301,7 +301,7 @@ def test_natural_assignment_to_nil
end
def test_natural_assignment_to_nil_with_primary_key
client = Client.create(:name => "Primary key client", :firm_name => companies(:first_firm).name)
client = Client.create(name: "Primary key client", firm_name: companies(:first_firm).name)
client.firm_with_primary_key = nil
client.save
client.association(:firm_with_primary_key).reload
@ -330,14 +330,14 @@ def test_polymorphic_association_class
sponsor.association(:sponsorable).reload
assert_nil sponsor.sponsorable
sponsor.sponsorable = Member.new :name => "Bert"
sponsor.sponsorable = Member.new name: "Bert"
assert_equal Member, sponsor.association(:sponsorable).send(:klass)
assert_equal "members", sponsor.association(:sponsorable).aliased_table_name
end
def test_with_polymorphic_and_condition
sponsor = Sponsor.create
member = Member.create :name => "Bert"
member = Member.create name: "Bert"
sponsor.sponsorable = member
assert_equal member, sponsor.sponsorable
@ -346,7 +346,7 @@ def test_with_polymorphic_and_condition
def test_with_select
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
assert_equal 1, Company.all.merge!(includes: :firm_with_select ).find(2).firm_with_select.attributes.size
end
def test_belongs_to_without_counter_cache_option
@ -461,8 +461,8 @@ def test_belongs_to_reassign_with_namespaced_models_and_counters
end
def test_belongs_to_counter_after_save
topic = Topic.create!(:title => "monday night")
topic.replies.create!(:title => "re: monday night", :content => "football")
topic = Topic.create!(title: "monday night")
topic.replies.create!(title: "re: monday night", content: "football")
assert_equal 1, Topic.find(topic.id)[:replies_count]
topic.save!
@ -564,8 +564,8 @@ def test_belongs_to_counter_after_update
end
def test_belongs_to_counter_when_update_columns
topic = Topic.create!(:title => "37s")
topic.replies.create!(:title => "re: 37s", :content => "rails")
topic = Topic.create!(title: "37s")
topic.replies.create!(title: "re: 37s", content: "rails")
assert_equal 1, Topic.find(topic.id)[:replies_count]
topic.update_columns(content: "rails is wonderful")
@ -601,7 +601,7 @@ def test_assignment_before_child_saved_with_primary_key
def test_new_record_with_foreign_key_but_no_object
client = 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.all.merge!(:order => "id").first, client.firm_with_basic_id
assert_equal Firm.all.merge!(order: "id").first, client.firm_with_basic_id
end
def test_setting_foreign_key_after_nil_target_loaded
@ -632,10 +632,10 @@ def test_field_name_same_as_foreign_key
end
def test_counter_cache
topic = Topic.create :title => "Zoom-zoom-zoom"
topic = Topic.create title: "Zoom-zoom-zoom"
assert_equal 0, topic[:replies_count]
reply = Reply.create(:title => "re: zoom", :content => "speedy quick!")
reply = Reply.create(title: "re: zoom", content: "speedy quick!")
reply.topic = topic
assert_equal 1, topic.reload[:replies_count]
@ -646,10 +646,10 @@ def test_counter_cache
end
def test_counter_cache_double_destroy
topic = Topic.create :title => "Zoom-zoom-zoom"
topic = Topic.create title: "Zoom-zoom-zoom"
5.times do
topic.replies.create(:title => "re: zoom", :content => "speedy quick!")
topic.replies.create(title: "re: zoom", content: "speedy quick!")
end
assert_equal 5, topic.reload[:replies_count]
@ -666,10 +666,10 @@ def test_counter_cache_double_destroy
end
def test_concurrent_counter_cache_double_destroy
topic = Topic.create :title => "Zoom-zoom-zoom"
topic = Topic.create title: "Zoom-zoom-zoom"
5.times do
topic.replies.create(:title => "re: zoom", :content => "speedy quick!")
topic.replies.create(title: "re: zoom", content: "speedy quick!")
end
assert_equal 5, topic.reload[:replies_count]
@ -687,10 +687,10 @@ def test_concurrent_counter_cache_double_destroy
end
def test_custom_counter_cache
reply = Reply.create(:title => "re: zoom", :content => "speedy quick!")
reply = Reply.create(title: "re: zoom", content: "speedy quick!")
assert_equal 0, reply[:replies_count]
silly = SillyReply.create(:title => "gaga", :content => "boo-boo")
silly = SillyReply.create(title: "gaga", content: "boo-boo")
silly.reply = reply
assert_equal 1, reply.reload[:replies_count]
@ -714,7 +714,7 @@ def test_replace_counter_cache
def test_association_assignment_sticks
post = Post.first
author1, author2 = Author.all.merge!(:limit => 2).to_a
author1, author2 = Author.all.merge!(limit: 2).to_a
assert_not_nil author1
assert_not_nil author2
@ -767,7 +767,7 @@ def test_polymorphic_assignment_foreign_type_field_updating
def test_polymorphic_assignment_with_primary_key_foreign_type_field_updating
# should update when assigning a saved record
essay = Essay.new
writer = Author.create(:name => "David")
writer = Author.create(name: "David")
essay.writer = writer
assert_equal "Author", essay.writer_type
@ -792,7 +792,7 @@ def test_polymorphic_assignment_updates_foreign_id_field_for_new_and_saved_recor
def test_assignment_updates_foreign_id_field_for_new_and_saved_records
client = Client.new
saved_firm = Firm.create :name => "Saved"
saved_firm = Firm.create name: "Saved"
new_firm = Firm.new
client.firm = saved_firm
@ -804,7 +804,7 @@ def test_assignment_updates_foreign_id_field_for_new_and_saved_records
def test_polymorphic_assignment_with_primary_key_updates_foreign_id_field_for_new_and_saved_records
essay = Essay.new
saved_writer = Author.create(:name => "David")
saved_writer = Author.create(name: "David")
new_writer = Author.new
essay.writer = saved_writer
@ -842,14 +842,14 @@ def test_save_of_record_with_loaded_belongs_to
assert_nothing_raised do
Account.find(@account.id).save!
Account.all.merge!(: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.all.merge!(:includes => :firm).find(@account.id).save!
Account.all.merge!(includes: :firm).find(@account.id).save!
end
end
@ -870,18 +870,18 @@ def test_dependent_delete_and_destroy_with_belongs_to
def test_belongs_to_invalid_dependent_option_raises_exception
error = assert_raise ArgumentError do
Class.new(Author).belongs_to :special_author_address, :dependent => :nullify
Class.new(Author).belongs_to :special_author_address, dependent: :nullify
end
assert_equal error.message, "The :dependent option must be one of [:destroy, :delete], but is :nullify"
end
def test_attributes_are_being_set_when_initialized_from_belongs_to_association_with_where_clause
new_firm = accounts(:signals37).build_firm(:name => "Apple")
new_firm = accounts(:signals37).build_firm(name: "Apple")
assert_equal new_firm.name, "Apple"
end
def test_attributes_are_set_without_error_when_initialized_from_belongs_to_association_with_array_in_where_clause
new_account = Account.where(:credit_limit => [ 50, 60 ]).new
new_account = Account.where(credit_limit: [ 50, 60 ]).new
assert_nil new_account.credit_limit
end
@ -1002,42 +1002,42 @@ def test_create_bang_with_conditions
end
def test_build_with_block
client = Client.create(:name => "Client Company")
client = Client.create(name: "Client Company")
firm = client.build_firm{ |f| f.name = "Agency Company" }
assert_equal "Agency Company", firm.name
end
def test_create_with_block
client = Client.create(:name => "Client Company")
client = Client.create(name: "Client Company")
firm = client.create_firm{ |f| f.name = "Agency Company" }
assert_equal "Agency Company", firm.name
end
def test_create_bang_with_block
client = Client.create(:name => "Client Company")
client = Client.create(name: "Client Company")
firm = client.create_firm!{ |f| f.name = "Agency Company" }
assert_equal "Agency Company", firm.name
end
def test_should_set_foreign_key_on_create_association
client = Client.create! :name => "fuu"
client = Client.create! name: "fuu"
firm = client.create_firm :name => "baa"
firm = client.create_firm name: "baa"
assert_equal firm.id, client.client_of
end
def test_should_set_foreign_key_on_create_association!
client = Client.create! :name => "fuu"
client = Client.create! name: "fuu"
firm = client.create_firm! :name => "baa"
firm = client.create_firm! name: "baa"
assert_equal firm.id, client.client_of
end
def test_self_referential_belongs_to_with_counter_cache_assigning_nil
comment = Comment.create! :post => posts(:thinking), :body => "fuu"
comment = Comment.create! post: posts(:thinking), body: "fuu"
comment.parent = nil
comment.save!
@ -1058,7 +1058,7 @@ def test_belongs_to_with_id_assigning
def test_polymorphic_with_custom_primary_key
toy = Toy.create!
sponsor = Sponsor.create!(:sponsorable => toy)
sponsor = Sponsor.create!(sponsorable: toy)
assert_equal toy, sponsor.reload.sponsorable
end
@ -1077,7 +1077,7 @@ def test_polymorphic_with_custom_primary_key
def test_reflect_the_most_recent_change
author1, author2 = Author.limit(2)
post = Post.new(:title => "foo", :body=> "bar")
post = Post.new(title: "foo", body: "bar")
post.author = author1
post.author_id = author2.id

@ -61,20 +61,20 @@ def test_multiple_callbacks
end
def test_has_many_callbacks_with_create
morten = Author.create :name => "Morten"
post = morten.posts_with_proc_callbacks.create! :title => "Hello", :body => "How are you doing?"
morten = Author.create name: "Morten"
post = morten.posts_with_proc_callbacks.create! title: "Hello", body: "How are you doing?"
assert_equal ["before_adding<new>", "after_adding#{post.id}"], morten.post_log
end
def test_has_many_callbacks_with_create!
morten = Author.create! :name => "Morten"
post = morten.posts_with_proc_callbacks.create :title => "Hello", :body => "How are you doing?"
morten = Author.create! name: "Morten"
post = morten.posts_with_proc_callbacks.create title: "Hello", body: "How are you doing?"
assert_equal ["before_adding<new>", "after_adding#{post.id}"], morten.post_log
end
def test_has_many_callbacks_for_save_on_parent
jack = Author.new :name => "Jack"
jack.posts_with_callbacks.build :title => "Call me back!", :body => "Before you wake up and after you sleep"
jack = Author.new name: "Jack"
jack.posts_with_callbacks.build title: "Call me back!", body: "Before you wake up and after you sleep"
callback_log = ["before_adding<new>", "after_adding#{jack.posts_with_callbacks.first.id}"]
assert_equal callback_log, jack.post_log
@ -84,8 +84,8 @@ def test_has_many_callbacks_for_save_on_parent
end
def test_has_many_callbacks_for_destroy_on_parent
firm = Firm.create! :name => "Firm"
client = firm.clients.create! :name => "Client"
firm = Firm.create! name: "Firm"
client = firm.clients.create! name: "Client"
firm.destroy
assert_equal ["before_remove#{client.id}", "after_remove#{client.id}"], firm.log
@ -108,14 +108,14 @@ def test_has_and_belongs_to_many_before_add_called_before_save
klass = Class.new(Project) do
def self.name; Project.name; end
has_and_belongs_to_many :developers_with_callbacks,
:class_name => "Developer",
:before_add => lambda { |o,r|
class_name: "Developer",
before_add: lambda { |o,r|
dev = r
new_dev = r.new_record?
}
end
rec = klass.create!
alice = Developer.new(:name => "alice")
alice = Developer.new(name: "alice")
rec.developers_with_callbacks << alice
assert_equal alice, dev
assert_not_nil new_dev
@ -126,14 +126,14 @@ def self.name; Project.name; end
def test_has_and_belongs_to_many_after_add_called_after_save
ar = projects(:active_record)
assert ar.developers_log.empty?
alice = Developer.new(:name => "alice")
alice = Developer.new(name: "alice")
ar.developers_with_callbacks << alice
assert_equal"after_adding#{alice.id}", ar.developers_log.last
bob = ar.developers_with_callbacks.create(:name => "bob")
bob = ar.developers_with_callbacks.create(name: "bob")
assert_equal "after_adding#{bob.id}", ar.developers_log.last
ar.developers_with_callbacks.build(:name => "charlie")
ar.developers_with_callbacks.build(name: "charlie")
assert_equal "after_adding<new>", ar.developers_log.last
end
@ -166,8 +166,8 @@ def test_has_and_belongs_to_many_does_not_fire_callbacks_on_clear
end
def test_has_many_and_belongs_to_many_callbacks_for_save_on_parent
project = Project.new :name => "Callbacks"
project.developers_with_callbacks.build :name => "Jack", :salary => 95000
project = Project.new name: "Callbacks"
project.developers_with_callbacks.build name: "Jack", salary: 95000
callback_log = ["before_adding<new>", "after_adding<new>"]
assert_equal callback_log, project.developers_log

@ -16,7 +16,7 @@ class CascadedEagerLoadingTest < ActiveRecord::TestCase
:categorizations, :people, :categories, :edges, :vertices
def test_eager_association_loading_with_cascaded_two_levels
authors = Author.all.merge!(:includes=>{:posts=>:comments}, :order=>"authors.id").to_a
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 @@ def test_eager_association_loading_with_cascaded_two_levels
end
def test_eager_association_loading_with_cascaded_two_levels_and_one_level
authors = Author.all.merge!(:includes=>[{:posts=>:comments}, :categorizations], :order=>"authors.id").to_a
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,22 +35,22 @@ def test_eager_association_loading_with_cascaded_two_levels_and_one_level
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 => {:tags_count => 1}).to_a
Author.joins(:posts).eager_load(:comments).where(posts: {tags_count: 1}).to_a
end
authors = Author.joins(:posts).eager_load(:comments).where(:posts => {:tags_count => 1}).to_a
authors = Author.joins(:posts).eager_load(:comments).where(posts: {tags_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").to_a
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
assert_equal people(:michael), Person.eager_load(primary_contact: :primary_contact).where("primary_contacts_people_2.first_name = ?", "Susan").order("people.id").first
end
def test_cascaded_eager_association_loading_with_join_for_count
categories = Category.joins(:categorizations).includes([{:posts=>:comments}, :authors])
categories = Category.joins(:categorizations).includes([{posts: :comments}, :authors])
assert_equal 4, categories.count
assert_equal 4, categories.to_a.count
@ -59,7 +59,7 @@ def test_cascaded_eager_association_loading_with_join_for_count
end
def test_cascaded_eager_association_loading_with_duplicated_includes
categories = Category.includes(:categorizations).includes(:categorizations => :author).where("categorizations.id is not null").references(:categorizations)
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.to_a.size
@ -67,7 +67,7 @@ def test_cascaded_eager_association_loading_with_duplicated_includes
end
def test_cascaded_eager_association_loading_with_twice_includes_edge_cases
categories = Category.includes(:categorizations => :author).includes(:categorizations => :post).where("posts.id is not null").references(:posts)
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.to_a.size
@ -82,7 +82,7 @@ def test_eager_association_loading_with_join_for_count
end
def test_eager_association_loading_with_cascaded_two_levels_with_two_has_many_associations
authors = Author.all.merge!(:includes=>{:posts=>[:comments, :categorizations]}, :order=>"authors.id").to_a
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
@ -90,7 +90,7 @@ def test_eager_association_loading_with_cascaded_two_levels_with_two_has_many_as
end
def test_eager_association_loading_with_cascaded_two_levels_and_self_table_reference
authors = Author.all.merge!(:includes=>{:posts=>[:comments, :author]}, :order=>"authors.id").to_a
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
@ -98,13 +98,13 @@ def test_eager_association_loading_with_cascaded_two_levels_and_self_table_refer
end
def test_eager_association_loading_with_cascaded_two_levels_with_condition
authors = Author.all.merge!(:includes=>{:posts=>:comments}, :where=>"authors.id=1", :order=>"authors.id").to_a
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.all.merge!(:includes=>{:account=>{:firm=>:account}}, :order=>"companies.id").to_a
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 }
@ -112,7 +112,7 @@ def test_eager_association_loading_with_cascaded_three_levels_by_ping_pong
end
def test_eager_association_loading_with_has_many_sti
topics = Topic.all.merge!(:includes => :replies, :order => "topics.id").to_a
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
@ -121,11 +121,11 @@ def test_eager_association_loading_with_has_many_sti
end
def test_eager_association_loading_with_has_many_sti_and_subclasses
silly = SillyReply.new(:title => "gaga", :content => "boo-boo", :parent_id => 1)
silly = SillyReply.new(title: "gaga", content: "boo-boo", parent_id: 1)
silly.parent_id = 1
assert silly.save
topics = Topic.all.merge!(:includes => :replies, :order => ["topics.id", "replies_topics.id"]).to_a
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
@ -133,14 +133,14 @@ def test_eager_association_loading_with_has_many_sti_and_subclasses
end
def test_eager_association_loading_with_belongs_to_sti
replies = Reply.all.merge!(:includes => :topic, :order => "topics.id").to_a
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.all.merge!(: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
@ -149,7 +149,7 @@ def test_eager_association_loading_with_multiple_stis_and_order
end
def test_eager_association_loading_of_stis_with_multiple_references
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
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
@ -158,7 +158,7 @@ def test_eager_association_loading_of_stis_with_multiple_references
end
def test_eager_association_loading_where_first_level_returns_nil
authors = Author.all.merge!(:includes => {:post_about_thinking => :comments}, :order => "authors.id DESC").to_a
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
@ -166,12 +166,12 @@ def test_eager_association_loading_where_first_level_returns_nil
end
def test_eager_association_loading_with_recursive_cascading_four_levels_has_many_through
source = Vertex.all.merge!(: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.all.merge!(: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

@ -5,7 +5,7 @@
module Namespaced
class Post < ActiveRecord::Base
self.table_name = "posts"
has_one :tagging, :as => :taggable, :class_name => "Tagging"
has_one :tagging, as: :taggable, class_name: "Tagging"
end
end
@ -16,8 +16,8 @@ def setup
end
def generate_test_objects
post = Namespaced::Post.create( :title => "Great stuff", :body => "This is not", :author_id => 1 )
Tagging.create( :taggable => post )
post = Namespaced::Post.create( title: "Great stuff", body: "This is not", author_id: 1 )
Tagging.create( taggable: post )
end
def test_class_names

@ -23,30 +23,30 @@ def sample; @@remembered.sample; end
end
class ShapeExpression < ActiveRecord::Base
belongs_to :shape, :polymorphic => true
belongs_to :paint, :polymorphic => true
belongs_to :shape, polymorphic: true
belongs_to :paint, polymorphic: true
end
class Circle < ActiveRecord::Base
has_many :shape_expressions, :as => :shape
has_many :shape_expressions, as: :shape
include Remembered
end
class Square < ActiveRecord::Base
has_many :shape_expressions, :as => :shape
has_many :shape_expressions, as: :shape
include Remembered
end
class Triangle < ActiveRecord::Base
has_many :shape_expressions, :as => :shape
has_many :shape_expressions, as: :shape
include Remembered
end
class PaintColor < ActiveRecord::Base
has_many :shape_expressions, :as => :paint
belongs_to :non_poly, :foreign_key => "non_poly_one_id", :class_name => "NonPolyOne"
has_many :shape_expressions, as: :paint
belongs_to :non_poly, foreign_key: "non_poly_one_id", class_name: "NonPolyOne"
include Remembered
end
class PaintTexture < ActiveRecord::Base
has_many :shape_expressions, :as => :paint
belongs_to :non_poly, :foreign_key => "non_poly_two_id", :class_name => "NonPolyTwo"
has_many :shape_expressions, as: :paint
belongs_to :non_poly, foreign_key: "non_poly_two_id", class_name: "NonPolyTwo"
include Remembered
end
class NonPolyOne < ActiveRecord::Base
@ -78,19 +78,19 @@ def generate_test_object_graphs
[Circle, Square, Triangle, NonPolyOne, NonPolyTwo].map(&:create!)
end
1.upto(NUM_SIMPLE_OBJS) do
PaintColor.create!(:non_poly_one_id => NonPolyOne.sample.id)
PaintTexture.create!(:non_poly_two_id => NonPolyTwo.sample.id)
PaintColor.create!(non_poly_one_id: NonPolyOne.sample.id)
PaintTexture.create!(non_poly_two_id: NonPolyTwo.sample.id)
end
1.upto(NUM_SHAPE_EXPRESSIONS) do
shape_type = [Circle, Square, Triangle].sample
paint_type = [PaintColor, PaintTexture].sample
ShapeExpression.create!(:shape_type => shape_type.to_s, :shape_id => shape_type.sample.id,
:paint_type => paint_type.to_s, :paint_id => paint_type.sample.id)
ShapeExpression.create!(shape_type: shape_type.to_s, shape_id: shape_type.sample.id,
paint_type: paint_type.to_s, paint_id: paint_type.sample.id)
end
end
def test_include_query
res = ShapeExpression.all.merge!(:includes => [ :shape, { :paint => :non_poly } ]).to_a
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|
@ -103,10 +103,10 @@ def test_include_query
class EagerLoadNestedIncludeWithMissingDataTest < ActiveRecord::TestCase
def setup
@davey_mcdave = Author.create(:name => "Davey McDave")
@first_post = @davey_mcdave.posts.create(:title => "Davey Speaks", :body => "Expressive wordage")
@first_comment = @first_post.comments.create(:body => "Inflamatory doublespeak")
@first_categorization = @davey_mcdave.categorizations.create(:category => Category.first, :post => @first_post)
@davey_mcdave = Author.create(name: "Davey McDave")
@first_post = @davey_mcdave.posts.create(title: "Davey Speaks", body: "Expressive wordage")
@first_comment = @first_post.comments.create(body: "Inflamatory doublespeak")
@first_categorization = @davey_mcdave.categorizations.create(category: Category.first, post: @first_post)
end
teardown do
@ -119,8 +119,8 @@ def setup
def test_missing_data_in_a_nested_include_should_not_cause_errors_when_constructing_objects
assert_nothing_raised do
# @davey_mcdave doesn't have any author_favorites
includes = {:posts => :comments, :categorizations => :category, :author_favorites => :favorite_author }
Author.all.merge!(:includes => includes, :where => {:authors => {:name => @davey_mcdave.name}}, :order => "categories.name").to_a
includes = {posts: :comments, categorizations: :category, author_favorites: :favorite_author }
Author.all.merge!(includes: includes, where: {authors: {name: @davey_mcdave.name}}, order: "categories.name").to_a
end
end
end

@ -25,10 +25,10 @@ class Mess < ActiveRecord::Base
class Crisis < ActiveRecord::Base
has_and_belongs_to_many :messes
has_many :analyses, :dependent => :destroy
has_many :successes, :through => :analyses
has_many :dresses, :dependent => :destroy
has_many :compresses, :through => :dresses
has_many :analyses, dependent: :destroy
has_many :successes, through: :analyses
has_many :dresses, dependent: :destroy
has_many :compresses, through: :dresses
end
class Analysis < ActiveRecord::Base
@ -37,8 +37,8 @@ class Analysis < ActiveRecord::Base
end
class Success < ActiveRecord::Base
has_many :analyses, :dependent => :destroy
has_many :crises, :through => :analyses
has_many :analyses, dependent: :destroy
has_many :crises, through: :analyses
end
class Dress < ActiveRecord::Base
@ -65,7 +65,7 @@ def setup
connection.create_table :buses do |t|
t.column :name, :string
end
connection.create_table :crises_messes, :id => false do |t|
connection.create_table :crises_messes, id: false do |t|
t.column :crisis_id, :integer
t.column :mess_id, :integer
end
@ -110,38 +110,38 @@ def connection
def test_eager_no_extra_singularization_belongs_to
assert_nothing_raised do
Virus.all.merge!(:includes => :octopus).to_a
Virus.all.merge!(includes: :octopus).to_a
end
end
def test_eager_no_extra_singularization_has_one
assert_nothing_raised do
Octopus.all.merge!(:includes => :virus).to_a
Octopus.all.merge!(includes: :virus).to_a
end
end
def test_eager_no_extra_singularization_has_many
assert_nothing_raised do
Bus.all.merge!(:includes => :passes).to_a
Bus.all.merge!(includes: :passes).to_a
end
end
def test_eager_no_extra_singularization_has_and_belongs_to_many
assert_nothing_raised do
Crisis.all.merge!(:includes => :messes).to_a
Mess.all.merge!(:includes => :crises).to_a
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
assert_nothing_raised do
Crisis.all.merge!(:includes => :successes).to_a
Crisis.all.merge!(includes: :successes).to_a
end
end
def test_eager_no_extra_singularization_has_many_through_has_many
assert_nothing_raised do
Crisis.all.merge!(:includes => :compresses).to_a
Crisis.all.merge!(includes: :compresses).to_a
end
end
end

@ -34,42 +34,42 @@ class EagerAssociationTest < ActiveRecord::TestCase
:developers, :projects, :developers_projects, :members, :memberships, :clubs, :sponsors
def test_eager_with_has_one_through_join_model_with_conditions_on_the_through
member = Member.all.merge!(: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.all.merge!(:includes => :comments).to_a
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.all.merge!(: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.all.merge!(:includes => :last_comment).to_a
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.all.merge!(:includes => :last_comment, :order => "comments.id DESC").to_a
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).merge(
:includes => :comments,
:where => "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE} = 'SpecialComment'"
includes: :comments,
where: "comments.body like 'Normal%' OR comments.#{QUOTED_TYPE} = 'SpecialComment'"
).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.all.merge!(:includes => :comments, :order => "posts.id DESC").to_a
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|
@ -100,14 +100,14 @@ def test_with_two_tables_in_from_without_getting_double_quoted
end
def test_loading_with_multiple_associations
posts = Post.all.merge!(:includes => [ :comments, :author, :categories ], :order => "posts.id").to_a
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.all.merge!(:where => "post_id = 1", :includes => [:post => :author]).to_a
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
@ -115,28 +115,28 @@ def test_duplicate_middle_objects
def test_preloading_has_many_in_multiple_queries_with_more_ids_than_database_can_handle
assert_called(Comment.connection, :in_clause_length, returns: 5) do
posts = Post.all.merge!(:includes=>:comments).to_a
posts = Post.all.merge!(includes: :comments).to_a
assert_equal 11, posts.size
end
end
def test_preloading_has_many_in_one_queries_when_database_has_no_limit_on_ids_it_can_handle
assert_called(Comment.connection, :in_clause_length, returns: nil) do
posts = Post.all.merge!(:includes=>:comments).to_a
posts = Post.all.merge!(includes: :comments).to_a
assert_equal 11, posts.size
end
end
def test_preloading_habtm_in_multiple_queries_with_more_ids_than_database_can_handle
assert_called(Comment.connection, :in_clause_length, times: 2, returns: 5) do
posts = Post.all.merge!(:includes=>:categories).to_a
posts = Post.all.merge!(includes: :categories).to_a
assert_equal 11, posts.size
end
end
def test_preloading_habtm_in_one_queries_when_database_has_no_limit_on_ids_it_can_handle
assert_called(Comment.connection, :in_clause_length, times: 2, returns: nil) do
posts = Post.all.merge!(:includes=>:categories).to_a
posts = Post.all.merge!(includes: :categories).to_a
assert_equal 11, posts.size
end
end
@ -145,7 +145,7 @@ def test_load_associated_records_in_one_query_when_adapter_has_no_limit
assert_called(Comment.connection, :in_clause_length, returns: nil) do
post = posts(:welcome)
assert_queries(2) do
Post.includes(:comments).where(:id => post.id).to_a
Post.includes(:comments).where(id: post.id).to_a
end
end
end
@ -154,7 +154,7 @@ def test_load_associated_records_in_several_queries_when_many_ids_passed
assert_called(Comment.connection, :in_clause_length, returns: 1) do
post1, post2 = posts(:welcome), posts(:thinking)
assert_queries(3) do
Post.includes(:comments).where(:id => [post1.id, post2.id]).to_a
Post.includes(:comments).where(id: [post1.id, post2.id]).to_a
end
end
end
@ -163,50 +163,50 @@ def test_load_associated_records_in_one_query_when_a_few_ids_passed
assert_called(Comment.connection, :in_clause_length, returns: 3) do
post = posts(:welcome)
assert_queries(2) do
Post.includes(:comments).where(:id => post.id).to_a
Post.includes(:comments).where(id: post.id).to_a
end
end
end
def test_including_duplicate_objects_from_belongs_to
popular_post = Post.create!(:title => "foo", :body => "I like cars!")
comment = popular_post.comments.create!(:body => "lol")
popular_post.readers.create!(:person => people(:michael))
popular_post.readers.create!(:person => people(:david))
popular_post = Post.create!(title: "foo", body: "I like cars!")
comment = popular_post.comments.create!(body: "lol")
popular_post.readers.create!(person: people(:michael))
popular_post.readers.create!(person: people(:david))
readers = Reader.all.merge!(:where => ["post_id = ?", popular_post.id],
:includes => {:post => :comments}).to_a
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
end
def test_including_duplicate_objects_from_has_many
car_post = Post.create!(:title => "foo", :body => "I like cars!")
car_post = Post.create!(title: "foo", body: "I like cars!")
car_post.categories << categories(:general)
car_post.categories << categories(:technology)
comment = car_post.comments.create!(:body => "hmm")
categories = Category.all.merge!(:where => { "posts.id" => car_post.id },
:includes => {:posts => :comments}).to_a
comment = car_post.comments.create!(body: "hmm")
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
end
def test_associations_loaded_for_all_records
post = Post.create!(:title => "foo", :body => "I like cars!")
SpecialComment.create!(:body => "Come on!", :post => post)
first_category = Category.create! :name => "First!", :posts => [post]
second_category = Category.create! :name => "Second!", :posts => [post]
post = Post.create!(title: "foo", body: "I like cars!")
SpecialComment.create!(body: "Come on!", post: post)
first_category = Category.create! name: "First!", posts: [post]
second_category = Category.create! name: "Second!", posts: [post]
categories = Category.where(:id => [first_category.id, second_category.id]).includes(:posts => :special_comments)
categories = Category.where(id: [first_category.id, second_category.id]).includes(posts: :special_comments)
assert_equal categories.map { |category| category.posts.first.special_comments.loaded? }, [true, true]
end
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.all.merge!(: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!
@ -217,7 +217,7 @@ def test_finding_with_includes_on_has_one_association_with_same_include_includes
author = authors(:david)
post = author.post_about_thinking_with_last_comment
last_comment = post.last_comment
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
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
@ -228,7 +228,7 @@ def test_finding_with_includes_on_belongs_to_association_with_same_include_inclu
post = posts(:welcome)
author = post.author
author_address = author.author_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
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
@ -248,7 +248,7 @@ def test_finding_with_includes_on_null_belongs_to_association_with_same_include_
def test_finding_with_includes_on_null_belongs_to_polymorphic_association
sponsor = sponsors(:moustache_club_sponsor_for_groucho)
sponsor.update!(sponsorable: nil)
sponsor = assert_queries(1) { Sponsor.all.merge!(: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
@ -258,7 +258,7 @@ def test_finding_with_includes_on_empty_polymorphic_type_column
sponsor = sponsors(:moustache_club_sponsor_for_groucho)
sponsor.update!(sponsorable_type: "", sponsorable_id: nil) # sponsorable_type column might be declared NOT NULL
sponsor = assert_queries(1) do
assert_nothing_raised { Sponsor.all.merge!(:includes => :sponsorable).find(sponsor.id) }
assert_nothing_raised { Sponsor.all.merge!(includes: :sponsorable).find(sponsor.id) }
end
assert_no_queries do
assert_equal nil, sponsor.sponsorable
@ -266,25 +266,25 @@ def test_finding_with_includes_on_empty_polymorphic_type_column
end
def test_loading_from_an_association
posts = authors(:david).posts.merge(:includes => :comments, :order => "posts.id").to_a
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.all.merge!(:includes => :hello_posts_with_hash_conditions).to_a
Author.all.merge!(includes: :hello_posts_with_hash_conditions).to_a
end
assert !Author.all.merge!(: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.all.merge!(:includes => :author).find(posts(:authorless).id).author
assert_nil Post.all.merge!(includes: :author).find(posts(:authorless).id).author
end
# Regression test for 21c75e5
def test_nested_loading_does_not_raise_exception_when_association_does_not_exist
assert_nothing_raised do
Post.all.merge!(:includes => {:author => :author_addresss}).find(posts(:authorless).id)
Post.all.merge!(includes: {author: :author_addresss}).find(posts(:authorless).id)
end
end
@ -292,61 +292,61 @@ def test_three_level_nested_preloading_does_not_raise_exception_when_association
post_id = Comment.where(author_id: nil).where.not(post_id: nil).first.post_id
assert_nothing_raised do
Post.preload(:comments => [{:author => :essays}]).find(post_id)
Post.preload(comments: [{author: :essays}]).find(post_id)
end
end
def test_nested_loading_through_has_one_association
aa = AuthorAddress.all.merge!(: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.all.merge!(: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.all.merge!(: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.all.merge!(: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).merge(
:includes => {:author => :posts},
:where => "author_addresses.id > 0"
includes: {author: :posts},
where: "author_addresses.id > 0"
).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_on_association
aa = AuthorAddress.references(:authors).merge(
:includes => {:author => :posts},
:where => "authors.id > 0"
includes: {author: :posts},
where: "authors.id > 0"
).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_on_nested_association
aa = AuthorAddress.references(:posts).merge(
:includes => {:author => :posts},
:where => "posts.id > 0"
includes: {author: :posts},
where: "posts.id > 0"
).find author_addresses(:david_address).id
assert_equal aa.author.posts.count, aa.author.posts.length
end
def test_eager_association_loading_with_belongs_to_and_foreign_keys
pets = Pet.all.merge!(:includes => :owner).to_a
pets = Pet.all.merge!(includes: :owner).to_a
assert_equal 4, pets.length
end
def test_eager_association_loading_with_belongs_to
comments = Comment.all.merge!(:includes => :post).to_a
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)
@ -354,31 +354,31 @@ def test_eager_association_loading_with_belongs_to
end
def test_eager_association_loading_with_belongs_to_and_limit
comments = Comment.all.merge!(:includes => :post, :limit => 5, :order => "comments.id").to_a
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(&:id)
end
def test_eager_association_loading_with_belongs_to_and_limit_and_conditions
comments = Comment.all.merge!(:includes => :post, :where => "post_id = 4", :limit => 3, :order => "comments.id").to_a
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(&:id)
end
def test_eager_association_loading_with_belongs_to_and_limit_and_offset
comments = Comment.all.merge!(:includes => :post, :limit => 3, :offset => 2, :order => "comments.id").to_a
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(&:id)
end
def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_conditions
comments = Comment.all.merge!(:includes => :post, :where => "post_id = 4", :limit => 3, :offset => 1, :order => "comments.id").to_a
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(&:id)
end
def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_conditions_array
comments = Comment.all.merge!(:includes => :post, :where => ["post_id = ?",4], :limit => 3, :offset => 1, :order => "comments.id").to_a
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(&:id)
end
@ -392,7 +392,7 @@ def test_eager_association_loading_with_belongs_to_and_conditions_string_with_un
def test_eager_association_loading_with_belongs_to_and_conditions_hash
comments = []
assert_nothing_raised do
comments = Comment.all.merge!(:includes => :post, :where => {:posts => {:id => 4}}, :limit => 3, :order => "comments.id").to_a
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(&:id)
@ -410,7 +410,7 @@ def test_eager_association_loading_with_belongs_to_and_conditions_string_with_qu
def test_eager_association_loading_with_belongs_to_and_order_string_with_unquoted_table_name
assert_nothing_raised do
Comment.all.merge!(:includes => :post, :order => "posts.id").to_a
Comment.all.merge!(includes: :post, order: "posts.id").to_a
end
end
@ -422,19 +422,19 @@ def test_eager_association_loading_with_belongs_to_and_order_string_with_quoted_
end
def test_eager_association_loading_with_belongs_to_and_limit_and_multiple_associations
posts = Post.all.merge!(:includes => [:author, :very_special_comment], :limit => 1, :order => "posts.id").to_a
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(&:id)
end
def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_multiple_associations
posts = Post.all.merge!(:includes => [:author, :very_special_comment], :limit => 1, :offset => 1, :order => "posts.id").to_a
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(&:id)
end
def test_eager_association_loading_with_belongs_to_inferred_foreign_key_from_association_name
author_favorite = AuthorFavorite.all.merge!(: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
@ -445,26 +445,26 @@ def test_eager_load_belongs_to_quotes_table_and_column_names
end
def test_eager_load_has_one_quotes_table_and_column_names
michael = Person.all.merge!(:includes => :favourite_reference).find(people(:michael).id)
michael = Person.all.merge!(includes: :favourite_reference).find(people(:michael).id)
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.all.merge!(:includes => :references).find(people(:michael).id)
michael = Person.all.merge!(includes: :references).find(people(:michael).id)
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.all.merge!(:includes => :jobs).find(people(:michael).id)
michael = Person.all.merge!(includes: :jobs).find(people(:michael).id)
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.all.merge!(: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
@ -475,32 +475,32 @@ def test_string_id_column_joins
b = Book.create!
Subscription.create!(:subscriber_id => "PL", :book_id => b.id)
Subscription.create!(subscriber_id: "PL", book_id: b.id)
s.reload
s.book_ids = s.book_ids
end
def test_eager_load_has_many_through_with_string_keys
books = books(:awdr, :rfr)
subscriber = Subscriber.all.merge!(: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.all.merge!(: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.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
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.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
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 }
@ -508,35 +508,35 @@ def test_eager_with_has_many_through
def test_eager_with_has_many_through_a_belongs_to_association
author = authors(:mary)
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.merge(:includes => :author_favorites).to_a
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.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.all.merge!(: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.all.merge!(:includes => :special_nonexistent_post_comments, :order => "authors.id").first
author = Author.all.merge!(includes: :special_nonexistent_post_comments, order: "authors.id").first
assert_equal [], author.special_nonexistent_post_comments
end
def test_eager_with_has_many_through_join_model_with_conditions
assert_equal Author.all.merge!(:includes => :hello_post_comments,
:order => "authors.id").first.hello_post_comments.sort_by(&:id),
Author.all.merge!(:order => "authors.id").first.hello_post_comments.sort_by(&:id)
assert_equal Author.all.merge!(includes: :hello_post_comments,
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.all.merge!(: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.all.merge!(: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
@ -544,7 +544,7 @@ def test_eager_with_has_many_through_join_model_with_include
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.all.merge!(: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
@ -555,19 +555,19 @@ def test_eager_with_has_many_through_join_model_ignores_default_includes
end
def test_eager_with_has_many_and_limit
posts = Post.all.merge!(:order => "posts.id asc", :includes => [ :author, :comments ], :limit => 2).to_a
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
posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => "posts.body = 'hello'", :order => "posts.id").to_a
posts = Post.all.merge!(includes: [ :author, :comments ], limit: 2, where: "posts.body = 'hello'", order: "posts.id").to_a
assert_equal 2, posts.size
assert_equal [4,5], posts.collect(&:id)
end
def test_eager_with_has_many_and_limit_and_conditions_array
posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => [ "posts.body = ?", "hello" ], :order => "posts.id").to_a
posts = Post.all.merge!(includes: [ :author, :comments ], limit: 2, where: [ "posts.body = ?", "hello" ], order: "posts.id").to_a
assert_equal 2, posts.size
assert_equal [4,5], posts.collect(&:id)
end
@ -581,34 +581,34 @@ def test_eager_with_has_many_and_limit_and_conditions_array_on_the_eagers
end
def test_eager_with_has_many_and_limit_and_high_offset
posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :offset => 10, :where => { "authors.name" => "David" }).to_a
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).
merge(:includes => [ :author, :comments ], :limit => 2, :offset => 10,
:where => [ "authors.name = ? and comments.body = ?", "David", "go crazy" ]).to_a
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.all.merge!(:includes => [ :author, :comments ], :limit => 2, :offset => 10,
:where => { "authors.name" => "David", "comments.body" => "go crazy" }).to_a
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.all.merge!(: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.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => "posts.title = 'magic forest'").to_a
posts = Post.all.merge!(includes: [ :author, :comments ], limit: 2, where: "posts.title = 'magic forest'").to_a
assert_equal 0, posts.size
end
@ -625,7 +625,7 @@ def test_eager_count_performed_on_a_has_many_through_association_with_multi_tabl
end
def test_eager_with_has_and_belongs_to_many_and_limit
posts = Post.all.merge!(:includes => :categories, :order => "posts.id", :limit => 3).to_a
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
@ -691,7 +691,7 @@ def test_eager_with_has_many_and_limit_and_scoped_conditions_on_the_eagers
end
def test_eager_association_loading_with_habtm
posts = Post.all.merge!(:includes => :categories, :order => "posts.id").to_a
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
@ -700,23 +700,23 @@ def test_eager_association_loading_with_habtm
end
def test_eager_with_inheritance
SpecialPost.all.merge!(:includes => [ :comments ]).to_a
SpecialPost.all.merge!(includes: [ :comments ]).to_a
end
def test_eager_has_one_with_association_inheritance
post = Post.all.merge!(: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.all.merge!(: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.all.merge!(: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
@ -725,8 +725,8 @@ def test_eager_habtm_with_association_inheritance
def test_eager_with_has_one_dependent_does_not_destroy_dependent
assert_not_nil companies(:first_firm).account
f = Firm.all.merge!(:includes => :account,
:where => ["companies.name = ?", "37signals"]).first
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
end
@ -740,16 +740,16 @@ def test_eager_with_multi_table_conditional_properly_counts_the_records_when_usi
def test_eager_with_invalid_association_reference
assert_raise(ActiveRecord::AssociationNotFoundError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
Post.all.merge!(:includes=> :monkeys ).find(6)
Post.all.merge!(includes: :monkeys ).find(6)
}
assert_raise(ActiveRecord::AssociationNotFoundError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
Post.all.merge!(:includes=>[ :monkeys ]).find(6)
Post.all.merge!(includes: [ :monkeys ]).find(6)
}
assert_raise(ActiveRecord::AssociationNotFoundError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys") {
Post.all.merge!(:includes=>[ "monkeys" ]).find(6)
Post.all.merge!(includes: [ "monkeys" ]).find(6)
}
assert_raise(ActiveRecord::AssociationNotFoundError, "Association was not found; perhaps you misspelled it? You specified :include => :monkeys, :elephants") {
Post.all.merge!(:includes=>[ :monkeys, :elephants ]).find(6)
Post.all.merge!(includes: [ :monkeys, :elephants ]).find(6)
}
end
@ -786,7 +786,7 @@ def test_eager_has_many_through_multiple_with_order
end
def test_eager_with_default_scope
developer = EagerDeveloperWithDefaultScope.where(:name => "David").first
developer = EagerDeveloperWithDefaultScope.where(name: "David").first
projects = Project.order(:id).to_a
assert_no_queries do
assert_equal(projects, developer.projects)
@ -794,7 +794,7 @@ def test_eager_with_default_scope
end
def test_eager_with_default_scope_as_class_method
developer = EagerDeveloperWithClassMethodDefaultScope.where(:name => "David").first
developer = EagerDeveloperWithClassMethodDefaultScope.where(name: "David").first
projects = Project.order(:id).to_a
assert_no_queries do
assert_equal(projects, developer.projects)
@ -819,7 +819,7 @@ def test_eager_with_default_scope_as_class_method_using_find_by_method
end
def test_eager_with_default_scope_as_lambda
developer = EagerDeveloperWithLambdaDefaultScope.where(:name => "David").first
developer = EagerDeveloperWithLambdaDefaultScope.where(name: "David").first
projects = Project.order(:id).to_a
assert_no_queries do
assert_equal(projects, developer.projects)
@ -828,8 +828,8 @@ def test_eager_with_default_scope_as_lambda
def test_eager_with_default_scope_as_block
# warm up the habtm cache
EagerDeveloperWithBlockDefaultScope.where(:name => "David").first.projects
developer = EagerDeveloperWithBlockDefaultScope.where(:name => "David").first
EagerDeveloperWithBlockDefaultScope.where(name: "David").first.projects
developer = EagerDeveloperWithBlockDefaultScope.where(name: "David").first
projects = Project.order(:id).to_a
assert_no_queries do
assert_equal(projects, developer.projects)
@ -837,7 +837,7 @@ def test_eager_with_default_scope_as_block
end
def test_eager_with_default_scope_as_callable
developer = EagerDeveloperWithCallableDefaultScope.where(:name => "David").first
developer = EagerDeveloperWithCallableDefaultScope.where(name: "David").first
projects = Project.order(:id).to_a
assert_no_queries do
assert_equal(projects, developer.projects)
@ -845,22 +845,22 @@ def test_eager_with_default_scope_as_callable
end
def find_all_ordered(className, include=nil)
className.all.merge!(:order=>"#{className.table_name}.#{className.primary_key}", :includes=>include).to_a
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.all.merge!(
:includes => [:author, :comments], :where => { "authors.name" => "David" },
:order => "UPPER(posts.title)", :limit => 2, :offset => 1
includes: [:author, :comments], where: { "authors.name" => "David" },
order: "UPPER(posts.title)", limit: 2, offset: 1
).to_a
)
assert_equal(
posts(:sti_post_and_comments, :sti_comments),
Post.all.merge!(
:includes => [:author, :comments], :where => { "authors.name" => "David" },
:order => "UPPER(posts.title) DESC", :limit => 2, :offset => 1
includes: [:author, :comments], where: { "authors.name" => "David" },
order: "UPPER(posts.title) DESC", limit: 2, offset: 1
).to_a
)
end
@ -869,15 +869,15 @@ def test_limited_eager_with_multiple_order_columns
assert_equal(
posts(:thinking, :sti_comments),
Post.all.merge!(
:includes => [:author, :comments], :where => { "authors.name" => "David" },
:order => ["UPPER(posts.title)", "posts.id"], :limit => 2, :offset => 1
includes: [:author, :comments], where: { "authors.name" => "David" },
order: ["UPPER(posts.title)", "posts.id"], limit: 2, offset: 1
).to_a
)
assert_equal(
posts(:sti_post_and_comments, :sti_comments),
Post.all.merge!(
:includes => [:author, :comments], :where => { "authors.name" => "David" },
:order => ["UPPER(posts.title) DESC", "posts.id"], :limit => 2, :offset => 1
includes: [:author, :comments], where: { "authors.name" => "David" },
order: ["UPPER(posts.title) DESC", "posts.id"], limit: 2, offset: 1
).to_a
)
end
@ -886,17 +886,17 @@ def test_limited_eager_with_numeric_in_association
assert_equal(
people(:david, :susan),
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
includes: [:readers, :primary_contact, :number1_fan],
where: "number1_fans_people.first_name like 'M%'",
order: "people.id", limit: 2, offset: 0
).to_a
)
end
def test_polymorphic_type_condition
post = Post.all.merge!(: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.all.merge!(:includes => :taggings).find(posts(:thinking).id)
post = SpecialPost.all.merge!(includes: :taggings).find(posts(:thinking).id)
assert post.taggings.include?(taggings(:thinking_general))
end
@ -947,13 +947,13 @@ def test_eager_with_multiple_associations_with_same_table_belongs_to
end
end
def test_eager_with_valid_association_as_string_not_symbol
assert_nothing_raised { Post.all.merge!(:includes => "comments").to_a }
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.all.merge!(:where => "123.456 = 123.456", :includes => :post).to_a
Comment.all.merge!(where: "123.456 = 123.456", includes: :post).to_a
end
end
@ -1007,12 +1007,12 @@ def test_count_with_include
def test_association_loading_notification
notifications = messages_for("instantiation.active_record") do
Developer.all.merge!(:includes => "projects", :where => { "developers_projects.access_level" => 1 }, :limit => 5).to_a.size
Developer.all.merge!(includes: "projects", where: { "developers_projects.access_level" => 1 }, limit: 5).to_a.size
end
message = notifications.first
payload = message.last
count = Developer.all.merge!(:includes => "projects", :where => { "developers_projects.access_level" => 1 }, :limit => 5).to_a.size
count = Developer.all.merge!(includes: "projects", where: { "developers_projects.access_level" => 1 }, limit: 5).to_a.size
# eagerloaded row count should be greater than just developer count
assert_operator payload[:record_count], :>, count
@ -1048,22 +1048,22 @@ def test_load_with_sti_sharing_association
end
def test_conditions_on_join_table_with_include_and_limit
assert_equal 3, Developer.all.merge!(:includes => "projects", :where => { "developers_projects.access_level" => 1 }, :limit => 5).to_a.size
assert_equal 3, Developer.all.merge!(includes: "projects", where: { "developers_projects.access_level" => 1 }, limit: 5).to_a.size
end
def test_dont_create_temporary_active_record_instances
Developer.instance_count = 0
developers = Developer.all.merge!(:includes => "projects", :where => { "developers_projects.access_level" => 1 }, :limit => 5).to_a
developers = Developer.all.merge!(includes: "projects", where: { "developers_projects.access_level" => 1 }, limit: 5).to_a
assert_equal developers.count, Developer.instance_count
end
def test_order_on_join_table_with_include_and_limit
assert_equal 5, Developer.all.merge!(:includes => "projects", :order => "developers_projects.joined_on DESC", :limit => 5).to_a.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.all.merge!(:joins => :comments, :includes => :author, :order => "comments.id DESC").to_a
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}
@ -1071,32 +1071,32 @@ def test_eager_loading_with_order_on_joined_table_preloads
def test_eager_loading_with_conditions_on_joined_table_preloads
posts = assert_queries(2) do
Post.all.merge!(:select => "distinct posts.*", :includes => :author, :joins => [:comments], :where => "comments.body like 'Thank you%'", :order => "posts.id").to_a
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.all.merge!(:select => "distinct posts.*", :includes => :author, :joins => [:comments], :where => "comments.body like 'Thank you%'", :order => "posts.id").to_a
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.all.merge!(:includes => :author, :joins => {:taggings => :tag}, :where => "tags.name = 'General'", :order => "posts.id").to_a
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.all.merge!(:includes => :author, :joins => {:taggings => {:tag => :taggings}}, :where => "taggings_tags.super_tag_id=2", :order => "posts.id").to_a
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_preload_has_many_with_association_condition_and_default_scope
post = Post.create!(:title => "Beaches", :body => "I like beaches!")
Reader.create! :person => people(:david), :post => post
LazyReader.create! :person => people(:susan), :post => post
post = Post.create!(title: "Beaches", body: "I like beaches!")
Reader.create! person: people(:david), post: post
LazyReader.create! person: people(:susan), post: post
assert_equal 1, post.lazy_readers.to_a.size
assert_equal 2, post.lazy_readers_skimmers_or_not.to_a.size
@ -1107,13 +1107,13 @@ def test_preload_has_many_with_association_condition_and_default_scope
def test_eager_loading_with_conditions_on_string_joined_table_preloads
posts = assert_queries(2) do
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
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.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
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}
@ -1121,7 +1121,7 @@ def test_eager_loading_with_conditions_on_string_joined_table_preloads
def test_eager_loading_with_select_on_joined_table_preloads
posts = assert_queries(2) do
Post.all.merge!(:select => "posts.*, authors.name as author_name", :includes => :comments, :joins => :author, :order => "posts.id").to_a
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}
@ -1129,14 +1129,14 @@ def test_eager_loading_with_select_on_joined_table_preloads
def test_eager_loading_with_conditions_on_join_model_preloads
authors = assert_queries(2) do
Author.all.merge!(:includes => :author_address, :joins => :comments, :where => "posts.title like 'Welcome%'").to_a
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.merge(:includes => :primary_contact).to_a
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}
@ -1163,9 +1163,9 @@ def test_include_has_many_using_primary_key
expected = Firm.find(1).clients_using_primary_key.sort_by(&:name)
# Oracle adapter truncates alias to 30 characters
if current_adapter?(:OracleAdapter)
firm = Firm.all.merge!(: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.all.merge!(: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
@ -1174,7 +1174,7 @@ def test_include_has_many_using_primary_key
def test_preload_has_one_using_primary_key
expected = accounts(:signals37)
firm = Firm.all.merge!(: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
@ -1182,35 +1182,35 @@ def test_preload_has_one_using_primary_key
def test_include_has_one_using_primary_key
expected = accounts(:signals37)
firm = Firm.all.merge!(:includes => :account_using_primary_key, :order => "accounts.id").to_a.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
end
def test_preloading_empty_belongs_to
c = Client.create!(:name => "Foo", :client_of => Company.maximum(:id) + 1)
c = Client.create!(name: "Foo", client_of: Company.maximum(:id) + 1)
client = assert_queries(2) { Client.preload(:firm).find(c.id) }
assert_no_queries { assert_nil client.firm }
end
def test_preloading_empty_belongs_to_polymorphic
t = Tagging.create!(:taggable_type => "Post", :taggable_id => Post.maximum(:id) + 1, :tag => tags(:general))
t = Tagging.create!(taggable_type: "Post", taggable_id: Post.maximum(:id) + 1, tag: tags(:general))
tagging = assert_queries(2) { Tagging.preload(:taggable).find(t.id) }
assert_no_queries { assert_nil tagging.taggable }
end
def test_preloading_through_empty_belongs_to
c = Client.create!(:name => "Foo", :client_of => Company.maximum(:id) + 1)
c = Client.create!(name: "Foo", client_of: Company.maximum(:id) + 1)
client = assert_queries(2) { Client.preload(:accounts).find(c.id) }
assert_no_queries { assert client.accounts.empty? }
end
def test_preloading_has_many_through_with_distinct
mary = Author.includes(:unique_categorized_posts).where(:id => authors(:mary).id).first
mary = Author.includes(:unique_categorized_posts).where(id: authors(:mary).id).first
assert_equal 1, mary.unique_categorized_posts.length
assert_equal 1, mary.unique_categorized_post_ids.length
end
@ -1238,7 +1238,7 @@ def test_preloading_polymorphic_with_custom_foreign_type
groucho = members(:groucho)
sponsor = assert_queries(2) {
Sponsor.includes(:thing).where(:id => sponsor.id).first
Sponsor.includes(:thing).where(id: sponsor.id).first
}
assert_no_queries { assert_equal groucho, sponsor.thing }
end
@ -1253,16 +1253,16 @@ def test_joins_with_includes_should_preload_via_joins
def test_join_eager_with_empty_order_should_generate_valid_sql
assert_nothing_raised do
Post.includes(:comments).order("").where(:comments => {:body => "Thank you for the welcome"}).first
Post.includes(:comments).order("").where(comments: {body: "Thank you for the welcome"}).first
end
end
def test_deep_including_through_habtm
# warm up habtm cache
posts = Post.all.merge!(:includes => {:categories => :categorizations}, :order => "posts.id").to_a
posts = Post.all.merge!(includes: {categories: :categorizations}, order: "posts.id").to_a
posts[0].categories[0].categorizations.length
posts = Post.all.merge!(:includes => {:categories => :categorizations}, :order => "posts.id").to_a
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 }
@ -1279,12 +1279,12 @@ def test_eager_load_multiple_associations_with_references
end
test "scoping with a circular preload" do
assert_equal Comment.find(1), Comment.preload(:post => :comments).scoping { Comment.find(1) }
assert_equal Comment.find(1), Comment.preload(post: :comments).scoping { Comment.find(1) }
end
test "circular preload does not modify unscoped" do
expected = FirstPost.unscoped.find(2)
FirstPost.preload(:comments => :first_post).find(1)
FirstPost.preload(comments: :first_post).find(1)
assert_equal expected, FirstPost.unscoped.find(2)
end

@ -34,10 +34,10 @@
class ProjectWithAfterCreateHook < ActiveRecord::Base
self.table_name = "projects"
has_and_belongs_to_many :developers,
:class_name => "DeveloperForProjectWithAfterCreateHook",
:join_table => "developers_projects",
:foreign_key => "project_id",
:association_foreign_key => "developer_id"
class_name: "DeveloperForProjectWithAfterCreateHook",
join_table: "developers_projects",
foreign_key: "project_id",
association_foreign_key: "developer_id"
after_create :add_david
@ -50,36 +50,36 @@ def add_david
class DeveloperForProjectWithAfterCreateHook < ActiveRecord::Base
self.table_name = "developers"
has_and_belongs_to_many :projects,
:class_name => "ProjectWithAfterCreateHook",
:join_table => "developers_projects",
:association_foreign_key => "project_id",
:foreign_key => "developer_id"
class_name: "ProjectWithAfterCreateHook",
join_table: "developers_projects",
association_foreign_key: "project_id",
foreign_key: "developer_id"
end
class ProjectWithSymbolsForKeys < ActiveRecord::Base
self.table_name = "projects"
has_and_belongs_to_many :developers,
:class_name => "DeveloperWithSymbolsForKeys",
:join_table => :developers_projects,
:foreign_key => :project_id,
:association_foreign_key => "developer_id"
class_name: "DeveloperWithSymbolsForKeys",
join_table: :developers_projects,
foreign_key: :project_id,
association_foreign_key: "developer_id"
end
class DeveloperWithSymbolsForKeys < ActiveRecord::Base
self.table_name = "developers"
has_and_belongs_to_many :projects,
:class_name => "ProjectWithSymbolsForKeys",
:join_table => :developers_projects,
:association_foreign_key => :project_id,
:foreign_key => "developer_id"
class_name: "ProjectWithSymbolsForKeys",
join_table: :developers_projects,
association_foreign_key: :project_id,
foreign_key: "developer_id"
end
class SubDeveloper < Developer
self.table_name = "developers"
has_and_belongs_to_many :special_projects,
:join_table => "developers_projects",
:foreign_key => "project_id",
:association_foreign_key => "developer_id"
join_table: "developers_projects",
foreign_key: "project_id",
association_foreign_key: "developer_id"
end
class DeveloperWithSymbolClassName < Developer
@ -112,11 +112,11 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
def setup_data_for_habtm_case
ActiveRecord::Base.connection.execute("delete from countries_treaties")
country = Country.new(:name => "India")
country = Country.new(name: "India")
country.country_id = "c1"
country.save!
treaty = Treaty.new(:name => "peace")
treaty = Treaty.new(name: "peace")
treaty.treaty_id = "t1"
country.treaties << treaty
end
@ -148,11 +148,11 @@ def test_proper_usage_of_primary_keys_and_join_table
end
def test_join_table_composite_primary_key_should_not_warn
country = Country.new(:name => "India")
country = Country.new(name: "India")
country.country_id = "c1"
country.save!
treaty = Treaty.new(:name => "peace")
treaty = Treaty.new(name: "peace")
treaty.treaty_id = "t1"
warning = capture(:stderr) do
country.treaties << treaty
@ -258,7 +258,7 @@ def test_habtm_adding_before_save
def test_habtm_saving_multiple_relationships
new_project = Project.new("name" => "Grimetime")
amount_of_developers = 4
developers = (0...amount_of_developers).collect {|i| Developer.create(:name => "JME #{i}") }.reverse
developers = (0...amount_of_developers).collect {|i| Developer.create(name: "JME #{i}") }.reverse
new_project.developer_ids = [developers[0].id, developers[1].id]
new_project.developers_with_callback_ids = [developers[2].id, developers[3].id]
@ -323,9 +323,9 @@ def test_new_aliased_to_build
end
def test_build_by_new_record
devel = Developer.new(:name => "Marcel", :salary => 75000)
devel.projects.build(:name => "Make bed")
proj2 = devel.projects.build(:name => "Lie in it")
devel = Developer.new(name: "Marcel", salary: 75000)
devel.projects.build(name: "Make bed")
proj2 = devel.projects.build(name: "Lie in it")
assert_equal devel.projects.last, proj2
assert !proj2.persisted?
devel.save
@ -348,9 +348,9 @@ def test_create
end
def test_create_by_new_record
devel = Developer.new(:name => "Marcel", :salary => 75000)
devel.projects.build(:name => "Make bed")
proj2 = devel.projects.build(:name => "Lie in it")
devel = Developer.new(name: "Marcel", salary: 75000)
devel.projects.build(name: "Make bed")
proj2 = devel.projects.build(name: "Lie in it")
assert_equal devel.projects.last, proj2
assert !proj2.persisted?
devel.save
@ -362,13 +362,13 @@ def test_create_by_new_record
def test_creation_respects_hash_condition
# in Oracle '' is saved as null therefore need to save ' ' in not null column
post = categories(:general).post_with_conditions.build(:body => " ")
post = categories(:general).post_with_conditions.build(body: " ")
assert post.save
assert_equal "Yet Another Testing Title", post.title
# in Oracle '' is saved as null therefore need to save ' ' in not null column
another_post = categories(:general).post_with_conditions.create(:body => " ")
another_post = categories(:general).post_with_conditions.create(body: " ")
assert another_post.persisted?
assert_equal "Yet Another Testing Title", another_post.title
@ -563,7 +563,7 @@ def test_include_checks_if_record_exists_if_target_not_loaded
def test_include_returns_false_for_non_matching_record_to_verify_scoping
project = projects(:active_record)
developer = Developer.create :name => "Bryan", :salary => 50_000
developer = Developer.create name: "Bryan", salary: 50_000
assert ! project.developers.loaded?
assert ! project.developers.include?(developer)
@ -577,9 +577,9 @@ def test_find_with_merged_options
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")
high_id_jamis = projects(:active_record).developers.create(name: "Jamis")
assert_equal high_id_jamis, projects(:active_record).developers.merge(: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
@ -596,7 +596,7 @@ def test_dynamic_find_all_should_respect_readonly_access
def test_new_with_values_in_collection
jamis = DeveloperForProjectWithAfterCreateHook.find_by_name("Jamis")
david = DeveloperForProjectWithAfterCreateHook.find_by_name("David")
project = ProjectWithAfterCreateHook.new(:name => "Cooking with Bertie")
project = ProjectWithAfterCreateHook.new(name: "Cooking with Bertie")
project.developers << jamis
project.save!
project.reload
@ -701,8 +701,8 @@ def test_join_table_alias
assert_equal(
3,
Developer.references(:developers_projects_join).merge(
:includes => {:projects => :developers},
:where => "projects_developers_projects_join.joined_on IS NOT NULL"
includes: {projects: :developers},
where: "projects_developers_projects_join.joined_on IS NOT NULL"
).to_a.size
)
end
@ -721,15 +721,15 @@ def test_join_with_group
assert_equal(
3,
Developer.references(:developers_projects_join).merge(
:includes => {:projects => :developers}, :where => "projects_developers_projects_join.joined_on IS NOT NULL",
:group => group.join(",")
includes: {projects: :developers}, where: "projects_developers_projects_join.joined_on IS NOT NULL",
group: group.join(",")
).to_a.size
)
end
def test_find_grouped
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
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
@ -796,8 +796,8 @@ def test_has_many_through_polymorphic_has_manys_works
end
def test_symbols_as_keys
developer = DeveloperWithSymbolsForKeys.new(:name => "David")
project = ProjectWithSymbolsForKeys.new(:name => "Rails Testing")
developer = DeveloperWithSymbolsForKeys.new(name: "David")
project = ProjectWithSymbolsForKeys.new(name: "Rails Testing")
project.developers << developer
project.save!
@ -842,12 +842,12 @@ def test_caching_of_columns
end
def test_attributes_are_being_set_when_initialized_from_habtm_association_with_where_clause
new_developer = projects(:action_controller).developers.where(:name => "Marcelo").build
new_developer = projects(:action_controller).developers.where(name: "Marcelo").build
assert_equal new_developer.name, "Marcelo"
end
def test_attributes_are_being_set_when_initialized_from_habtm_association_with_multiple_where_clauses
new_developer = projects(:action_controller).developers.where(:name => "Marcelo").where(:salary => 90_000).build
new_developer = projects(:action_controller).developers.where(name: "Marcelo").where(salary: 90_000).build
assert_equal new_developer.name, "Marcelo"
assert_equal new_developer.salary, 90_000
end

@ -65,7 +65,7 @@ def test_custom_primary_key_on_new_record_should_fetch_with_query
end
def test_association_primary_key_on_new_record_should_fetch_with_query
author = Author.new(:name => "David")
author = Author.new(name: "David")
assert !author.essays.loaded?
assert_queries 1 do
@ -121,9 +121,9 @@ def test_anonymous_has_many
developer_project = Class.new(ActiveRecord::Base) {
self.table_name = "developers_projects"
belongs_to :developer, :anonymous_class => dev
belongs_to :developer, anonymous_class: dev
}
has_many :developer_projects, :anonymous_class => developer_project, :foreign_key => "developer_id"
has_many :developer_projects, anonymous_class: developer_project, foreign_key: "developer_id"
}
dev = developer.first
named = Developer.find(dev.id)
@ -142,13 +142,13 @@ def test_default_scope_on_relations_is_not_cached
comments = Class.new(ActiveRecord::Base) {
self.table_name = "comments"
self.inheritance_column = "not_there"
belongs_to :post, :anonymous_class => post
belongs_to :post, anonymous_class: post
default_scope -> {
counter += 1
where("id = :inc", :inc => counter)
where("id = :inc", inc: counter)
}
}
has_many :comments, :anonymous_class => comments, :foreign_key => "post_id"
has_many :comments, anonymous_class: comments, foreign_key: "post_id"
}
assert_equal 0, counter
post = posts.first
@ -192,7 +192,7 @@ def test_clear_collection_should_not_change_updated_at
end
def test_create_from_association_should_respect_default_scope
car = Car.create(:name => "honda")
car = Car.create(name: "honda")
assert_equal "honda", car.name
bulb = Bulb.create
@ -229,7 +229,7 @@ def test_build_from_association_should_respect_scope
end
def test_create_from_association_with_nil_values_should_work
car = Car.create(:name => "honda")
car = Car.create(name: "honda")
bulb = car.bulbs.new(nil)
assert_equal "defaulty", bulb.name
@ -242,7 +242,7 @@ def test_create_from_association_with_nil_values_should_work
end
def test_do_not_call_callbacks_for_delete_all
car = Car.create(:name => "honda")
car = Car.create(name: "honda")
car.funky_bulbs.create!
assert_equal 1, car.funky_bulbs.count
assert_nothing_raised { car.reload.funky_bulbs.delete_all }
@ -251,11 +251,11 @@ def test_do_not_call_callbacks_for_delete_all
def test_delete_all_on_association_is_the_same_as_not_loaded
author = authors :david
author.thinking_posts.create!(:body => "test")
author.thinking_posts.create!(body: "test")
author.reload
expected_sql = capture_sql { author.thinking_posts.delete_all }
author.thinking_posts.create!(:body => "test")
author.thinking_posts.create!(body: "test")
author.reload
author.thinking_posts.inspect
loaded_sql = capture_sql { author.thinking_posts.delete_all }
@ -264,11 +264,11 @@ def test_delete_all_on_association_is_the_same_as_not_loaded
def test_delete_all_on_association_with_nil_dependency_is_the_same_as_not_loaded
author = authors :david
author.posts.create!(:title => "test", :body => "body")
author.posts.create!(title: "test", body: "body")
author.reload
expected_sql = capture_sql { author.posts.delete_all }
author.posts.create!(:title => "test", :body => "body")
author.posts.create!(title: "test", body: "body")
author.reload
author.posts.to_a
loaded_sql = capture_sql { author.posts.delete_all }
@ -283,24 +283,24 @@ def test_building_the_associated_object_with_implicit_sti_base_class
def test_building_the_associated_object_with_explicit_sti_base_class
firm = DependentFirm.new
company = firm.companies.build(:type => "Company")
company = firm.companies.build(type: "Company")
assert_kind_of Company, company, "Expected #{company.class} to be a Company"
end
def test_building_the_associated_object_with_sti_subclass
firm = DependentFirm.new
company = firm.companies.build(:type => "Client")
company = firm.companies.build(type: "Client")
assert_kind_of Client, company, "Expected #{company.class} to be a Client"
end
def test_building_the_associated_object_with_an_invalid_type
firm = DependentFirm.new
assert_raise(ActiveRecord::SubclassNotFound) { firm.companies.build(:type => "Invalid") }
assert_raise(ActiveRecord::SubclassNotFound) { firm.companies.build(type: "Invalid") }
end
def test_building_the_associated_object_with_an_unrelated_type
firm = DependentFirm.new
assert_raise(ActiveRecord::SubclassNotFound) { firm.companies.build(:type => "Account") }
assert_raise(ActiveRecord::SubclassNotFound) { firm.companies.build(type: "Account") }
end
test "building the association with an array" do
@ -314,24 +314,24 @@ def test_building_the_associated_object_with_an_unrelated_type
end
def test_association_keys_bypass_attribute_protection
car = Car.create(:name => "honda")
car = Car.create(name: "honda")
bulb = car.bulbs.new
assert_equal car.id, bulb.car_id
bulb = car.bulbs.new :car_id => car.id + 1
bulb = car.bulbs.new car_id: car.id + 1
assert_equal car.id, bulb.car_id
bulb = car.bulbs.build
assert_equal car.id, bulb.car_id
bulb = car.bulbs.build :car_id => car.id + 1
bulb = car.bulbs.build car_id: car.id + 1
assert_equal car.id, bulb.car_id
bulb = car.bulbs.create
assert_equal car.id, bulb.car_id
bulb = car.bulbs.create :car_id => car.id + 1
bulb = car.bulbs.create car_id: car.id + 1
assert_equal car.id, bulb.car_id
end
@ -341,19 +341,19 @@ def test_association_protect_foreign_key
line_item = invoice.line_items.new
assert_equal invoice.id, line_item.invoice_id
line_item = invoice.line_items.new :invoice_id => invoice.id + 1
line_item = invoice.line_items.new invoice_id: invoice.id + 1
assert_equal invoice.id, line_item.invoice_id
line_item = invoice.line_items.build
assert_equal invoice.id, line_item.invoice_id
line_item = invoice.line_items.build :invoice_id => invoice.id + 1
line_item = invoice.line_items.build invoice_id: invoice.id + 1
assert_equal invoice.id, line_item.invoice_id
line_item = invoice.line_items.create
assert_equal invoice.id, line_item.invoice_id
line_item = invoice.line_items.create :invoice_id => invoice.id + 1
line_item = invoice.line_items.create invoice_id: invoice.id + 1
assert_equal invoice.id, line_item.invoice_id
end
@ -374,7 +374,7 @@ def test_build_and_create_should_not_happen_within_scope
end
def test_no_sql_should_be_fired_if_association_already_loaded
Car.create(:name => "honda")
Car.create(name: "honda")
bulbs = Car.first.bulbs
bulbs.to_a # to load all instances of bulbs
@ -425,13 +425,13 @@ def test_no_sql_should_be_fired_if_association_already_loaded
end
def test_create_resets_cached_counters
person = Person.create!(:first_name => "tenderlove")
person = Person.create!(first_name: "tenderlove")
post = Post.first
assert_equal [], person.readers
assert_nil person.readers.find_by_post_id(post.id)
person.readers.create(:post_id => post.id)
person.readers.create(post_id: post.id)
assert_equal 1, person.readers.count
assert_equal 1, person.readers.length
@ -461,19 +461,19 @@ def test_exists_respects_association_scope
# 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 3, Firm.all.merge!(:order => "id").first.clients.count
assert_equal 3, Firm.all.merge!(order: "id").first.clients.count
end
def test_counting
assert_equal 3, Firm.all.merge!(:order => "id").first.plain_clients.count
assert_equal 3, Firm.all.merge!(order: "id").first.plain_clients.count
end
def test_counting_with_single_hash
assert_equal 1, Firm.all.merge!(: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 3, Firm.all.merge!(:order => "id").first.plain_clients.count(:name)
assert_equal 3, Firm.all.merge!(order: "id").first.plain_clients.count(:name)
end
def test_counting_with_association_limit
@ -483,7 +483,7 @@ def test_counting_with_association_limit
end
def test_finding
assert_equal 3, Firm.all.merge!(:order => "id").first.clients.length
assert_equal 3, Firm.all.merge!(order: "id").first.clients.length
end
def test_finding_array_compatibility
@ -551,27 +551,27 @@ def test_cant_save_has_many_readonly_association
end
def test_finding_default_orders
assert_equal "Summit", Firm.all.merge!(: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 "Apex", Firm.all.merge!(:order => "id").first.clients_sorted_desc.first.name
assert_equal "Apex", Firm.all.merge!(order: "id").first.clients_sorted_desc.first.name
end
def test_finding_with_foreign_key
assert_equal "Microsoft", Firm.all.merge!(: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.all.merge!(: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.all.merge!(: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.all.merge!(: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_update_all_on_association_accessed_before_save
@ -599,7 +599,7 @@ def test_belongs_to_sanity
end
def test_find_ids
firm = Firm.all.merge!(:order => "id").first
firm = Firm.all.merge!(order: "id").first
assert_raise(ActiveRecord::RecordNotFound) { firm.clients.find }
@ -633,7 +633,7 @@ def test_find_ids_and_inverse_of
end
def test_find_all
firm = Firm.all.merge!(:order => "id").first
firm = Firm.all.merge!(order: "id").first
assert_equal 3, firm.clients.where("#{QUOTED_TYPE} = 'Client'").to_a.length
assert_equal 1, firm.clients.where("name = 'Summit'").to_a.length
end
@ -644,7 +644,7 @@ def test_find_each
assert ! firm.clients.loaded?
assert_queries(4) do
firm.clients.find_each(:batch_size => 1) {|c| assert_equal firm.id, c.firm_id }
firm.clients.find_each(batch_size: 1) {|c| assert_equal firm.id, c.firm_id }
end
assert ! firm.clients.loaded?
@ -669,7 +669,7 @@ def test_find_in_batches
assert ! firm.clients.loaded?
assert_queries(2) do
firm.clients.find_in_batches(:batch_size => 2) do |clients|
firm.clients.find_in_batches(batch_size: 2) do |clients|
clients.each {|c| assert_equal firm.id, c.firm_id }
end
end
@ -679,29 +679,29 @@ def test_find_in_batches
def test_find_all_sanitized
# sometimes tests on Oracle fail if ORDER BY is not provided therefore add always :order with :first
firm = Firm.all.merge!(:order => "id").first
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
assert_equal summit, firm.clients.where("name = :name", { name: "Summit" }).to_a
end
def test_find_first
firm = Firm.all.merge!(:order => "id").first
firm = Firm.all.merge!(order: "id").first
client2 = Client.find(2)
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.all.merge!(:order => "id").first
firm = Firm.all.merge!(order: "id").first
client2 = Client.find(2)
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
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.all.merge!(:joins => :audit_logs, :where => {"audit_logs.message" => nil, :name => "Smith"}).to_a
Developer.all.merge!(joins: :audit_logs, where: {"audit_logs.message" => nil, :name => "Smith"}).to_a
end
end
@ -711,8 +711,8 @@ def test_find_in_collection
end
def test_find_grouped
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
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 3, all_clients_of_firm1.size
assert_equal 1, grouped_clients_of_firm1.size
end
@ -760,7 +760,7 @@ def test_adding
def test_adding_using_create
first_firm = companies(:first_firm)
assert_equal 3, first_firm.plain_clients.size
first_firm.plain_clients.create(:name => "Natural Company")
first_firm.plain_clients.create(name: "Natural Company")
assert_equal 4, first_firm.plain_clients.length
assert_equal 4, first_firm.plain_clients.size
end
@ -768,7 +768,7 @@ def test_adding_using_create
def test_create_with_bang_on_has_many_when_parent_is_new_raises
error = assert_raise(ActiveRecord::RecordNotSaved) do
firm = Firm.new
firm.plain_clients.create! :name=>"Whoever"
firm.plain_clients.create! name: "Whoever"
end
assert_equal "You cannot call create unless the parent is saved", error.message
@ -777,7 +777,7 @@ def test_create_with_bang_on_has_many_when_parent_is_new_raises
def test_regular_create_on_has_many_when_parent_is_new_raises
error = assert_raise(ActiveRecord::RecordNotSaved) do
firm = Firm.new
firm.plain_clients.create :name=>"Whoever"
firm.plain_clients.create name: "Whoever"
end
assert_equal "You cannot call create unless the parent is saved", error.message
@ -785,7 +785,7 @@ def test_regular_create_on_has_many_when_parent_is_new_raises
def test_create_with_bang_on_has_many_raises_when_record_not_saved
assert_raise(ActiveRecord::RecordInvalid) do
firm = Firm.all.merge!(:order => "id").first
firm = Firm.all.merge!(order: "id").first
firm.plain_clients.create!
end
end
@ -815,8 +815,8 @@ def test_adding_a_collection
end
def test_transactions_when_adding_to_persisted
good = Client.new(:name => "Good")
bad = Client.new(:name => "Bad", :raise_on_save => true)
good = Client.new(name: "Good")
bad = Client.new(name: "Bad", raise_on_save: true)
begin
companies(:first_firm).clients_of_firm.concat(good, bad)
@ -905,7 +905,7 @@ def test_build_without_loading_association
assert_equal 1, first_topic.replies.length
assert_no_queries do
first_topic.replies.build(:title => "Not saved", :content => "Superstars")
first_topic.replies.build(title: "Not saved", content: "Superstars")
assert_equal 2, first_topic.replies.size
end
@ -944,7 +944,7 @@ def test_create_without_loading_association
first_firm.clients_of_firm.reset
assert_queries(1) do
first_firm.clients_of_firm.create(:name => "Superstars")
first_firm.clients_of_firm.create(name: "Superstars")
end
assert_equal 3, first_firm.clients_of_firm.size
@ -1104,10 +1104,10 @@ def test_calling_update_attributes_on_id_changes_the_counter_cache
assert_equal original_count, topic.replies_count
first_reply = topic.replies.first
first_reply.update_attributes(:parent_id => nil)
first_reply.update_attributes(parent_id: nil)
assert_equal original_count - 1, topic.reload.replies_count
first_reply.update_attributes(:parent_id => topic.id)
first_reply.update_attributes(parent_id: topic.id)
assert_equal original_count, topic.reload.replies_count
end
@ -1120,11 +1120,11 @@ def test_calling_update_attributes_changing_ids_doesnt_change_counter_cache
reply1 = topic1.replies.first
reply2 = topic2.replies.first
reply1.update_attributes(:parent_id => topic2.id)
reply1.update_attributes(parent_id: topic2.id)
assert_equal original_count1 - 1, topic1.reload.replies_count
assert_equal original_count2 + 1, topic2.reload.replies_count
reply2.update_attributes(:parent_id => topic1.id)
reply2.update_attributes(parent_id: topic1.id)
assert_equal original_count1, topic1.reload.replies_count
assert_equal original_count2, topic2.reload.replies_count
end
@ -1169,8 +1169,8 @@ def test_delete_all_with_not_yet_loaded_association_collection
end
def test_transaction_when_deleting_persisted
good = Client.new(:name => "Good")
bad = Client.new(:name => "Bad", :raise_on_destroy => true)
good = Client.new(name: "Good")
bad = Client.new(name: "Bad", raise_on_destroy: true)
companies(:first_firm).clients_of_firm = [good, bad]
@ -1278,8 +1278,8 @@ def test_clearing_an_exclusively_dependent_association_collection
def test_dependent_association_respects_optional_conditions_on_delete
firm = companies(:odegy)
Client.create(:client_of => firm.id, :name => "BigShot Inc.")
Client.create(:client_of => firm.id, :name => "SmallTime Inc.")
Client.create(client_of: firm.id, name: "BigShot Inc.")
Client.create(client_of: firm.id, name: "SmallTime Inc.")
# only one of two clients is included in the association due to the :conditions key
assert_equal 2, Client.where(client_of: firm.id).size
assert_equal 1, firm.dependent_conditional_clients_of_firm.size
@ -1290,8 +1290,8 @@ def test_dependent_association_respects_optional_conditions_on_delete
def test_dependent_association_respects_optional_sanitized_conditions_on_delete
firm = companies(:odegy)
Client.create(:client_of => firm.id, :name => "BigShot Inc.")
Client.create(:client_of => firm.id, :name => "SmallTime Inc.")
Client.create(client_of: firm.id, name: "BigShot Inc.")
Client.create(client_of: firm.id, name: "SmallTime Inc.")
# only one of two clients is included in the association due to the :conditions key
assert_equal 2, Client.where(client_of: firm.id).size
assert_equal 1, firm.dependent_sanitized_conditional_clients_of_firm.size
@ -1302,8 +1302,8 @@ def test_dependent_association_respects_optional_sanitized_conditions_on_delete
def test_dependent_association_respects_optional_hash_conditions_on_delete
firm = companies(:odegy)
Client.create(:client_of => firm.id, :name => "BigShot Inc.")
Client.create(:client_of => firm.id, :name => "SmallTime Inc.")
Client.create(client_of: firm.id, name: "BigShot Inc.")
Client.create(client_of: firm.id, name: "SmallTime Inc.")
# only one of two clients is included in the association due to the :conditions key
assert_equal 2, Client.where(client_of: firm.id).size
assert_equal 1, firm.dependent_sanitized_conditional_clients_of_firm.size
@ -1457,7 +1457,7 @@ def test_dependence
firm = companies(:first_firm)
assert_equal 3, firm.clients.size
firm.destroy
assert Client.all.merge!(:where => "firm_id=#{firm.id}").to_a.empty?
assert Client.all.merge!(where: "firm_id=#{firm.id}").to_a.empty?
end
def test_dependence_for_associations_with_hash_condition
@ -1467,7 +1467,7 @@ def test_dependence_for_associations_with_hash_condition
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.all.merge!(:order => "id").first
firm = Firm.all.merge!(order: "id").first
assert_equal 3, firm.clients.size
client = firm.clients.first
@ -1494,7 +1494,7 @@ def test_dependence_with_transaction_support_on_failure
firm.destroy rescue "do nothing"
assert_equal 3, Client.all.merge!(:where => "firm_id=#{firm.id}").to_a.size
assert_equal 3, Client.all.merge!(where: "firm_id=#{firm.id}").to_a.size
end
def test_dependence_on_account
@ -1518,13 +1518,13 @@ def test_depends_and_nullify
end
def test_restrict_with_exception
firm = RestrictedWithExceptionFirm.create!(:name => "restrict")
firm.companies.create(:name => "child")
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")
assert RestrictedWithExceptionFirm.exists?(name: "restrict")
assert firm.companies.exists?(name: "child")
end
def test_restrict_with_error_is_deprecated_using_key_many
@ -1548,8 +1548,8 @@ def test_restrict_with_error_is_deprecated_using_key_many
end
def test_restrict_with_error
firm = RestrictedWithErrorFirm.create!(:name => "restrict")
firm.companies.create(:name => "child")
firm = RestrictedWithErrorFirm.create!(name: "restrict")
firm.companies.create(name: "child")
assert !firm.companies.empty?
@ -1558,8 +1558,8 @@ def test_restrict_with_error
assert !firm.errors.empty?
assert_equal "Cannot delete record because dependent companies exist", firm.errors[:base].first
assert RestrictedWithErrorFirm.exists?(:name => "restrict")
assert firm.companies.exists?(:name => "child")
assert RestrictedWithErrorFirm.exists?(name: "restrict")
assert firm.companies.exists?(name: "child")
end
def test_restrict_with_error_with_locale
@ -1586,7 +1586,7 @@ def test_included_in_collection
end
def test_included_in_collection_for_new_records
client = Client.create(:name => "Persisted")
client = Client.create(name: "Persisted")
assert_nil client.client_of
assert_equal false, Firm.new.clients_of_firm.include?(client),
"includes a client that does not belong to any firm"
@ -1597,7 +1597,7 @@ def test_adding_array_and_collection
end
def test_replace_with_less
firm = Firm.all.merge!(:order => "id").first
firm = Firm.all.merge!(order: "id").first
firm.clients = [companies(:first_client)]
assert firm.save, "Could not save firm"
firm.reload
@ -1611,7 +1611,7 @@ def test_replace_with_less_and_dependent_nullify
end
def test_replace_with_new
firm = Firm.all.merge!(:order => "id").first
firm = Firm.all.merge!(order: "id").first
firm.clients = [companies(:second_client), Client.new("name" => "New Client")]
firm.save
firm.reload
@ -1648,8 +1648,8 @@ def test_replace_with_same_content
end
def test_transactions_when_replacing_on_persisted
good = Client.new(:name => "Good")
bad = Client.new(:name => "Bad", :raise_on_save => true)
good = Client.new(name: "Good")
bad = Client.new(name: "Bad", raise_on_save: true)
companies(:first_firm).clients_of_firm = [good]
@ -1712,7 +1712,7 @@ def test_set_ids_for_association_on_new_record_applies_association_correctly
contract_a = Contract.create!
contract_b = Contract.create!
Contract.create! # another contract
company = Company.new(:name => "Some Company")
company = Company.new(name: "Some Company")
company.contract_ids = [contract_a.id, contract_b.id]
assert_equal [contract_a.id, contract_b.id], company.contract_ids
@ -1724,7 +1724,7 @@ def test_set_ids_for_association_on_new_record_applies_association_correctly
end
def test_assign_ids_ignoring_blanks
firm = Firm.create!(:name => "Apple")
firm = Firm.create!(name: "Apple")
firm.client_ids = [companies(:first_client).id, nil, companies(:second_client).id, ""]
firm.save!
@ -1740,7 +1740,7 @@ def test_modifying_a_through_a_has_many_should_raise
[
lambda { authors(:mary).comment_ids = [comments(:greetings).id, comments(:more_greetings).id] },
lambda { authors(:mary).comments = [comments(:greetings), comments(:more_greetings)] },
lambda { authors(:mary).comments << Comment.create!(:body => "Yay", :post_id => 424242) },
lambda { authors(:mary).comments << Comment.create!(body: "Yay", post_id: 424242) },
lambda { authors(:mary).comments.delete(authors(:mary).comments.first) },
].each {|block| assert_raise(ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection, &block) }
end
@ -1781,7 +1781,7 @@ def test_include_checks_if_record_exists_if_target_not_loaded
def test_include_returns_false_for_non_matching_record_to_verify_scoping
firm = companies(:first_firm)
client = Client.create!(:name => "Not Associated")
client = Client.create!(name: "Not Associated")
assert ! firm.clients.loaded?
assert_equal false, firm.clients.include?(client)
@ -1810,7 +1810,7 @@ def test_calling_first_or_last_on_loaded_association_should_not_fetch_with_query
def test_calling_first_or_last_on_existing_record_with_build_should_load_association
firm = companies(:first_firm)
firm.clients.build(:name => "Foo")
firm.clients.build(name: "Foo")
assert !firm.clients.loaded?
assert_queries 1 do
@ -1824,7 +1824,7 @@ def test_calling_first_or_last_on_existing_record_with_build_should_load_associa
def test_calling_first_nth_or_last_on_existing_record_with_create_should_not_load_association
firm = companies(:first_firm)
firm.clients.create(:name => "Foo")
firm.clients.create(name: "Foo")
assert !firm.clients.loaded?
assert_queries 3 do
@ -1848,7 +1848,7 @@ def test_calling_first_nth_or_last_on_new_record_should_not_run_queries
def test_calling_first_or_last_with_integer_on_association_should_not_load_association
firm = companies(:first_firm)
firm.clients.create(:name => "Foo")
firm.clients.create(name: "Foo")
assert !firm.clients.loaded?
assert_queries 2 do
@ -1978,13 +1978,13 @@ def test_joins_with_namespaced_model_should_use_correct_type
old = ActiveRecord::Base.store_full_sti_class
ActiveRecord::Base.store_full_sti_class = true
firm = Namespaced::Firm.create({ :name => "Some Company" })
firm.clients.create({ :name => "Some Client" })
firm = Namespaced::Firm.create({ name: "Some Company" })
firm.clients.create({ name: "Some Client" })
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"
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
@ -2010,8 +2010,8 @@ def test_respond_to_private_class_methods
end
def test_creating_using_primary_key
firm = Firm.all.merge!(:order => "id").first
client = firm.clients_using_primary_key.create!(:name => "test")
firm = Firm.all.merge!(order: "id").first
client = firm.clients_using_primary_key.create!(name: "test")
assert_equal firm.name, client.firm_name
end
@ -2034,12 +2034,12 @@ class NullifyModel < ActiveRecord::Base
end
def test_attributes_are_being_set_when_initialized_from_has_many_association_with_where_clause
new_comment = posts(:welcome).comments.where(:body => "Some content").build
new_comment = posts(:welcome).comments.where(body: "Some content").build
assert_equal new_comment.body, "Some content"
end
def test_attributes_are_being_set_when_initialized_from_has_many_association_with_multiple_where_clauses
new_comment = posts(:welcome).comments.where(:body => "Some content").where(:type => "SpecialComment").build
new_comment = posts(:welcome).comments.where(body: "Some content").where(type: "SpecialComment").build
assert_equal new_comment.body, "Some content"
assert_equal new_comment.type, "SpecialComment"
assert_equal new_comment.post_id, posts(:welcome).id
@ -2053,7 +2053,7 @@ def test_include_method_in_has_many_association_should_return_true_for_instance_
def test_load_target_respects_protected_attributes
topic = Topic.create!
reply = topic.replies.create(:title => "reply 1")
reply = topic.replies.create(title: "reply 1")
reply.approved = false
reply.save!
@ -2080,7 +2080,7 @@ def test_to_a_should_dup_target
end
def test_merging_with_custom_attribute_writer
bulb = Bulb.new(:color => "red")
bulb = Bulb.new(color: "red")
assert_equal "RED!", bulb.color
car = Car.create!
@ -2090,13 +2090,13 @@ def test_merging_with_custom_attribute_writer
end
def test_abstract_class_with_polymorphic_has_many
post = SubStiPost.create! :title => "fooo", :body => "baa"
tagging = Tagging.create! :taggable => post
post = SubStiPost.create! title: "fooo", body: "baa"
tagging = Tagging.create! taggable: post
assert_equal [tagging], post.taggings
end
def test_with_polymorphic_has_many_with_custom_columns_name
post = Post.create! :title => "foo", :body => "bar"
post = Post.create! title: "foo", body: "bar"
image = Image.create!
post.images << image
@ -2106,7 +2106,7 @@ def test_with_polymorphic_has_many_with_custom_columns_name
def test_build_with_polymorphic_has_many_does_not_allow_to_override_type_and_id
welcome = posts(:welcome)
tagging = welcome.taggings.build(:taggable_id => 99, :taggable_type => "ShouldNotChange")
tagging = welcome.taggings.build(taggable_id: 99, taggable_type: "ShouldNotChange")
assert_equal welcome.id, tagging.taggable_id
assert_equal "Post", tagging.taggable_type
@ -2121,7 +2121,7 @@ def test_dont_call_save_callbacks_twice_on_has_many
end
def test_association_attributes_are_available_to_after_initialize
car = Car.create(:name => "honda")
car = Car.create(name: "honda")
bulb = car.bulbs.build
assert_equal car.id, bulb.attributes_after_initialize["car_id"]
@ -2144,7 +2144,7 @@ def test_attributes_are_set_when_initialized_from_polymorphic_has_many_null_rela
end
def test_replace
car = Car.create(:name => "honda")
car = Car.create(name: "honda")
bulb1 = car.bulbs.create
bulb2 = Bulb.create
@ -2155,7 +2155,7 @@ def test_replace
end
def test_replace_returns_target
car = Car.create(:name => "honda")
car = Car.create(name: "honda")
bulb1 = car.bulbs.create
bulb2 = car.bulbs.create
bulb3 = Bulb.create

@ -37,8 +37,8 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
# Dummies to force column loads so query counts are clean.
def setup
Person.create :first_name => "gummy"
Reader.create :person_id => 0, :post_id => 0
Person.create first_name: "gummy"
Reader.create person_id: 0, post_id: 0
end
def test_preload_sti_rhs_class
@ -70,7 +70,7 @@ def test_ordered_has_many_through
def self.name; "Person"; end
has_many :readers
has_many :posts, -> { order("posts.id DESC") }, :through => :readers
has_many :posts, -> { order("posts.id DESC") }, through: :readers
end
posts = person_prime.includes(:posts).first.posts
@ -106,8 +106,8 @@ def test_singleton_has_many_through
def test_no_pk_join_table_append
lesson, _, student = make_no_pk_hm_t
sicp = lesson.new(:name => "SICP")
ben = student.new(:name => "Ben Bitdiddle")
sicp = lesson.new(name: "SICP")
ben = student.new(name: "Ben Bitdiddle")
sicp.students << ben
assert sicp.save!
end
@ -115,9 +115,9 @@ def test_no_pk_join_table_append
def test_no_pk_join_table_delete
lesson, lesson_student, student = make_no_pk_hm_t
sicp = lesson.new(:name => "SICP")
ben = student.new(:name => "Ben Bitdiddle")
louis = student.new(:name => "Louis Reasoner")
sicp = lesson.new(name: "SICP")
ben = student.new(name: "Ben Bitdiddle")
louis = student.new(name: "Louis Reasoner")
sicp.students << ben
sicp.students << louis
assert sicp.save!
@ -139,8 +139,8 @@ def test_no_pk_join_model_callbacks
after_destroy_called = true
end
sicp = lesson.new(:name => "SICP")
ben = student.new(:name => "Ben Bitdiddle")
sicp = lesson.new(name: "SICP")
ben = student.new(name: "Ben Bitdiddle")
sicp.students << ben
assert sicp.save!
@ -156,10 +156,10 @@ def make_no_pk_hm_t
lesson_student = make_model "LessonStudent"
lesson_student.table_name = "lessons_students"
lesson_student.belongs_to :lesson, :anonymous_class => lesson
lesson_student.belongs_to :student, :anonymous_class => student
lesson.has_many :lesson_students, :anonymous_class => lesson_student
lesson.has_many :students, :through => :lesson_students, :anonymous_class => student
lesson_student.belongs_to :lesson, anonymous_class: lesson
lesson_student.belongs_to :student, anonymous_class: student
lesson.has_many :lesson_students, anonymous_class: lesson_student
lesson.has_many :students, through: :lesson_students, anonymous_class: student
[lesson, lesson_student, student]
end
@ -274,7 +274,7 @@ def test_associating_new
new_person = nil # so block binding catches it
assert_queries(0) do
new_person = Person.new :first_name => "bob"
new_person = Person.new first_name: "bob"
end
# Associating new records always saves them
@ -294,8 +294,8 @@ def test_associate_new_by_building
assert_queries(1) { posts(:thinking) }
assert_queries(0) do
posts(:thinking).people.build(:first_name => "Bob")
posts(:thinking).people.new(:first_name => "Ted")
posts(:thinking).people.build(first_name: "Bob")
posts(:thinking).people.new(first_name: "Ted")
end
# Should only need to load the association once
@ -318,7 +318,7 @@ def test_associate_new_by_building
def test_build_then_save_with_has_many_inverse
post = posts(:thinking)
person = post.people.build(:first_name => "Bob")
person = post.people.build(first_name: "Bob")
person.save
post.reload
@ -327,7 +327,7 @@ def test_build_then_save_with_has_many_inverse
def test_build_then_save_with_has_one_inverse
post = posts(:thinking)
person = post.single_people.build(:first_name => "Bob")
person = post.single_people.build(first_name: "Bob")
person.save
post.reload
@ -394,7 +394,7 @@ def test_delete_through_belongs_to_with_dependent_nullify
person = people(:michael)
job = jobs(:magician)
reference = Reference.where(:job_id => job.id, :person_id => person.id).first
reference = Reference.where(job_id: job.id, person_id: person.id).first
assert_no_difference ["Job.count", "Reference.count"] do
assert_difference "person.jobs.count", -1 do
@ -491,7 +491,7 @@ def test_belongs_to_with_dependent_nullify
def test_update_counter_caches_on_delete
post = posts(:welcome)
tag = post.tags.create!(:name => "doomed")
tag = post.tags.create!(name: "doomed")
assert_difference ["post.reload.tags_count"], -1 do
posts(:welcome).tags.delete(tag)
@ -500,7 +500,7 @@ def test_update_counter_caches_on_delete
def test_update_counter_caches_on_delete_with_dependent_destroy
post = posts(:welcome)
tag = post.tags.create!(:name => "doomed")
tag = post.tags.create!(name: "doomed")
post.update_columns(tags_with_destroy_count: post.tags.count)
assert_difference ["post.reload.tags_with_destroy_count"], -1 do
@ -510,7 +510,7 @@ def test_update_counter_caches_on_delete_with_dependent_destroy
def test_update_counter_caches_on_delete_with_dependent_nullify
post = posts(:welcome)
tag = post.tags.create!(:name => "doomed")
tag = post.tags.create!(name: "doomed")
post.update_columns(tags_with_nullify_count: post.tags.count)
assert_no_difference "post.reload.tags_count" do
@ -522,7 +522,7 @@ def test_update_counter_caches_on_delete_with_dependent_nullify
def test_update_counter_caches_on_replace_association
post = posts(:welcome)
tag = post.tags.create!(:name => "doomed")
tag = post.tags.create!(name: "doomed")
tag.tagged_posts << posts(:thinking)
tag.tagged_posts = []
@ -586,7 +586,7 @@ def test_associate_with_create
# 1 query for the new record, 1 for the join table record
# No need to update the actual collection yet!
assert_queries(2) do
posts(:thinking).people.create(:first_name=>"Jeb")
posts(:thinking).people.create(first_name: "Jeb")
end
# *Now* we actually need the collection so it's loaded
@ -605,55 +605,55 @@ def test_through_record_is_built_when_created_with_where
def test_associate_with_create_and_no_options
peeps = posts(:thinking).people.count
posts(:thinking).people.create(:first_name => "foo")
posts(:thinking).people.create(first_name: "foo")
assert_equal peeps + 1, posts(:thinking).people.count
end
def test_associate_with_create_with_through_having_conditions
impatient_people = posts(:thinking).impatient_people.count
posts(:thinking).impatient_people.create!(:first_name => "foo")
posts(:thinking).impatient_people.create!(first_name: "foo")
assert_equal impatient_people + 1, posts(:thinking).impatient_people.count
end
def test_associate_with_create_exclamation_and_no_options
peeps = posts(:thinking).people.count
posts(:thinking).people.create!(:first_name => "foo")
posts(:thinking).people.create!(first_name: "foo")
assert_equal peeps + 1, posts(:thinking).people.count
end
def test_create_on_new_record
p = Post.new
error = assert_raises(ActiveRecord::RecordNotSaved) { p.people.create(:first_name => "mew") }
error = assert_raises(ActiveRecord::RecordNotSaved) { p.people.create(first_name: "mew") }
assert_equal "You cannot call create unless the parent is saved", error.message
error = assert_raises(ActiveRecord::RecordNotSaved) { p.people.create!(:first_name => "snow") }
error = assert_raises(ActiveRecord::RecordNotSaved) { p.people.create!(first_name: "snow") }
assert_equal "You cannot call create unless the parent is saved", error.message
end
def test_associate_with_create_and_invalid_options
firm = companies(:first_firm)
assert_no_difference("firm.developers.count") { assert_nothing_raised { firm.developers.create(:name => "0") } }
assert_no_difference("firm.developers.count") { assert_nothing_raised { firm.developers.create(name: "0") } }
end
def test_associate_with_create_and_valid_options
firm = companies(:first_firm)
assert_difference("firm.developers.count", 1) { firm.developers.create(:name => "developer") }
assert_difference("firm.developers.count", 1) { firm.developers.create(name: "developer") }
end
def test_associate_with_create_bang_and_invalid_options
firm = companies(:first_firm)
assert_no_difference("firm.developers.count") { assert_raises(ActiveRecord::RecordInvalid) { firm.developers.create!(:name => "0") } }
assert_no_difference("firm.developers.count") { assert_raises(ActiveRecord::RecordInvalid) { firm.developers.create!(name: "0") } }
end
def test_associate_with_create_bang_and_valid_options
firm = companies(:first_firm)
assert_difference("firm.developers.count", 1) { firm.developers.create!(:name => "developer") }
assert_difference("firm.developers.count", 1) { firm.developers.create!(name: "developer") }
end
def test_push_with_invalid_record
firm = companies(:first_firm)
assert_raises(ActiveRecord::RecordInvalid) { firm.developers << Developer.new(:name => "0") }
assert_raises(ActiveRecord::RecordInvalid) { firm.developers << Developer.new(name: "0") }
end
def test_push_with_invalid_join_record
@ -661,10 +661,10 @@ def test_push_with_invalid_join_record
Contract.validate {|r| r.errors[:base] << "Invalid Contract" }
firm = companies(:first_firm)
lifo = Developer.new(:name => "lifo")
lifo = Developer.new(name: "lifo")
assert_raises(ActiveRecord::RecordInvalid) { firm.developers << lifo }
lifo = Developer.create!(:name => "lifo")
lifo = Developer.create!(name: "lifo")
assert_raises(ActiveRecord::RecordInvalid) { firm.developers << lifo }
end
end
@ -694,7 +694,7 @@ def test_association_callback_ordering
[:added, :after, "Michael"]
], log.last(2)
post.people_with_callbacks.push(people(:david), Person.create!(:first_name => "Bob"), Person.new(:first_name => "Lary"))
post.people_with_callbacks.push(people(:david), Person.create!(first_name: "Bob"), Person.new(first_name: "Lary"))
assert_equal [
[:added, :before, "David"],
[:added, :after, "David"],
@ -704,19 +704,19 @@ def test_association_callback_ordering
[:added, :after, "Lary"]
],log.last(6)
post.people_with_callbacks.build(:first_name => "Ted")
post.people_with_callbacks.build(first_name: "Ted")
assert_equal [
[:added, :before, "Ted"],
[:added, :after, "Ted"]
], log.last(2)
post.people_with_callbacks.create(:first_name => "Sam")
post.people_with_callbacks.create(first_name: "Sam")
assert_equal [
[:added, :before, "Sam"],
[:added, :after, "Sam"]
], log.last(2)
post.people_with_callbacks = [people(:michael),people(:david), Person.new(:first_name => "Julian"), Person.create!(:first_name => "Roger")]
post.people_with_callbacks = [people(:michael),people(:david), Person.new(first_name: "Julian"), Person.create!(first_name: "Roger")]
assert_equal((%w(Ted Bob Sam Lary) * 2).sort, log[-12..-5].collect(&:last).sort)
assert_equal [
[:added, :before, "Julian"],
@ -745,7 +745,7 @@ def test_get_ids
end
def test_get_ids_for_has_many_through_with_conditions_should_not_preload
Tagging.create!(:taggable_type => "Post", :taggable_id => posts(:welcome).id, :tag => tags(:misc))
Tagging.create!(taggable_type: "Post", taggable_id: posts(:welcome).id, tag: tags(:misc))
assert_not_called(ActiveRecord::Associations::Preloader, :new) do
posts(:welcome).misc_tag_ids
end
@ -776,16 +776,16 @@ def test_association_proxy_transaction_method_starts_transaction_in_association_
end
def test_has_many_association_through_a_belongs_to_association_where_the_association_doesnt_exist
post = Post.create!(:title => "TITLE", :body => "BODY")
post = Post.create!(title: "TITLE", body: "BODY")
assert_equal [], post.author_favorites
end
def test_has_many_association_through_a_belongs_to_association
author = authors(:mary)
post = Post.create!(:author => author, :title => "TITLE", :body => "BODY")
author.author_favorites.create(:favorite_author_id => 1)
author.author_favorites.create(:favorite_author_id => 2)
author.author_favorites.create(:favorite_author_id => 3)
post = Post.create!(author: author, title: "TITLE", body: "BODY")
author.author_favorites.create(favorite_author_id: 1)
author.author_favorites.create(favorite_author_id: 2)
author.author_favorites.create(favorite_author_id: 3)
assert_equal post.author.author_favorites, post.author_favorites
end
@ -809,36 +809,36 @@ def test_has_many_through_has_one_reflection
def test_modifying_has_many_through_has_one_reflection_should_raise
[
lambda { authors(:david).very_special_comments = [VerySpecialComment.create!(:body => "Gorp!", :post_id => 1011), VerySpecialComment.create!(:body => "Eep!", :post_id => 1012)] },
lambda { authors(:david).very_special_comments << VerySpecialComment.create!(:body => "Hoohah!", :post_id => 1013) },
lambda { authors(:david).very_special_comments = [VerySpecialComment.create!(body: "Gorp!", post_id: 1011), VerySpecialComment.create!(body: "Eep!", post_id: 1012)] },
lambda { authors(:david).very_special_comments << VerySpecialComment.create!(body: "Hoohah!", post_id: 1013) },
lambda { authors(:david).very_special_comments.delete(authors(:david).very_special_comments.first) },
].each {|block| assert_raise(ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection, &block) }
end
def test_has_many_association_through_a_has_many_association_to_self
sarah = Person.create!(:first_name => "Sarah", :primary_contact_id => people(:susan).id, :gender => "F", :number1_fan_id => 1)
john = Person.create!(:first_name => "John", :primary_contact_id => sarah.id, :gender => "M", :number1_fan_id => 1)
sarah = Person.create!(first_name: "Sarah", primary_contact_id: people(:susan).id, gender: "F", number1_fan_id: 1)
john = Person.create!(first_name: "John", primary_contact_id: sarah.id, gender: "M", number1_fan_id: 1)
assert_equal sarah.agents, [john]
assert_equal people(:susan).agents.flat_map(&:agents), people(:susan).agents_of_agents
end
def test_associate_existing_with_nonstandard_primary_key_on_belongs_to
Categorization.create(:author => authors(:mary), :named_category_name => categories(:general).name)
Categorization.create(author: authors(:mary), named_category_name: categories(:general).name)
assert_equal categories(:general), authors(:mary).named_categories.first
end
def test_collection_build_with_nonstandard_primary_key_on_belongs_to
author = authors(:mary)
category = author.named_categories.build(:name => "Primary")
category = author.named_categories.build(name: "Primary")
author.save
assert Categorization.exists?(:author_id => author.id, :named_category_name => category.name)
assert Categorization.exists?(author_id: author.id, named_category_name: category.name)
assert author.named_categories.reload.include?(category)
end
def test_collection_create_with_nonstandard_primary_key_on_belongs_to
author = authors(:mary)
category = author.named_categories.create(:name => "Primary")
assert Categorization.exists?(:author_id => author.id, :named_category_name => category.name)
category = author.named_categories.create(name: "Primary")
assert Categorization.exists?(author_id: author.id, named_category_name: category.name)
assert author.named_categories.reload.include?(category)
end
@ -851,9 +851,9 @@ def test_collection_exists
def test_collection_delete_with_nonstandard_primary_key_on_belongs_to
author = authors(:mary)
category = author.named_categories.create(:name => "Primary")
category = author.named_categories.create(name: "Primary")
author.named_categories.delete(category)
assert !Categorization.exists?(:author_id => author.id, :named_category_name => category.name)
assert !Categorization.exists?(author_id: author.id, named_category_name: category.name)
assert author.named_categories.reload.empty?
end
@ -890,16 +890,16 @@ def test_collection_singular_ids_setter_raises_exception_when_invalid_ids_set
end
def test_build_a_model_from_hm_through_association_with_where_clause
assert_nothing_raised { books(:awdr).subscribers.where(:nick => "marklazz").build }
assert_nothing_raised { books(:awdr).subscribers.where(nick: "marklazz").build }
end
def test_attributes_are_being_set_when_initialized_from_hm_through_association_with_where_clause
new_subscriber = books(:awdr).subscribers.where(:nick => "marklazz").build
new_subscriber = books(:awdr).subscribers.where(nick: "marklazz").build
assert_equal new_subscriber.nick, "marklazz"
end
def test_attributes_are_being_set_when_initialized_from_hm_through_association_with_multiple_where_clauses
new_subscriber = books(:awdr).subscribers.where(:nick => "marklazz").where(:name => "Marcelo Giorgi").build
new_subscriber = books(:awdr).subscribers.where(nick: "marklazz").where(name: "Marcelo Giorgi").build
assert_equal new_subscriber.nick, "marklazz"
assert_equal new_subscriber.name, "Marcelo Giorgi"
end
@ -960,12 +960,12 @@ def test_has_many_through_with_default_scope_on_join_model
end
def test_create_has_many_through_with_default_scope_on_join_model
category = authors(:david).special_categories.create(:name => "Foo")
assert_equal 1, category.categorizations.where(:special => true).count
category = authors(:david).special_categories.create(name: "Foo")
assert_equal 1, category.categorizations.where(special: true).count
end
def test_joining_has_many_through_with_distinct
mary = Author.joins(:unique_categorized_posts).where(:id => authors(:mary).id).first
mary = Author.joins(:unique_categorized_posts).where(id: authors(:mary).id).first
assert_equal 1, mary.unique_categorized_posts.length
assert_equal 1, mary.unique_categorized_post_ids.length
end
@ -1030,7 +1030,7 @@ def test_deleting_from_has_many_through_a_belongs_to_should_not_try_to_update_co
def test_primary_key_option_on_source
post = posts(:welcome)
category = categories(:general)
Categorization.create!(:post_id => post.id, :named_category_name => category.name)
Categorization.create!(post_id: post.id, named_category_name: category.name)
assert_equal [category], post.named_categories
assert_equal [category.name], post.named_category_ids # checks when target loaded
@ -1040,12 +1040,12 @@ def test_primary_key_option_on_source
def test_create_should_not_raise_exception_when_join_record_has_errors
repair_validations(Categorization) do
Categorization.validate { |r| r.errors[:base] << "Invalid Categorization" }
Category.create(:name => "Fishing", :authors => [Author.first])
Category.create(name: "Fishing", authors: [Author.first])
end
end
def test_assign_array_to_new_record_builds_join_records
c = Category.new(:name => "Fishing", :authors => [Author.first])
c = Category.new(name: "Fishing", authors: [Author.first])
assert_equal 1, c.categorizations.size
end
@ -1053,7 +1053,7 @@ def test_create_bang_should_raise_exception_when_join_record_has_errors
repair_validations(Categorization) do
Categorization.validate { |r| r.errors[:base] << "Invalid Categorization" }
assert_raises(ActiveRecord::RecordInvalid) do
Category.create!(:name => "Fishing", :authors => [Author.first])
Category.create!(name: "Fishing", authors: [Author.first])
end
end
end
@ -1061,7 +1061,7 @@ def test_create_bang_should_raise_exception_when_join_record_has_errors
def test_save_bang_should_raise_exception_when_join_record_has_errors
repair_validations(Categorization) do
Categorization.validate { |r| r.errors[:base] << "Invalid Categorization" }
c = Category.new(:name => "Fishing", :authors => [Author.first])
c = Category.new(name: "Fishing", authors: [Author.first])
assert_raises(ActiveRecord::RecordInvalid) do
c.save!
end
@ -1071,14 +1071,14 @@ def test_save_bang_should_raise_exception_when_join_record_has_errors
def test_save_returns_falsy_when_join_record_has_errors
repair_validations(Categorization) do
Categorization.validate { |r| r.errors[:base] << "Invalid Categorization" }
c = Category.new(:name => "Fishing", :authors => [Author.first])
c = Category.new(name: "Fishing", authors: [Author.first])
assert_not c.save
end
end
def test_preloading_empty_through_association_via_joins
person = Person.create!(:first_name => "Gaga")
person = Person.where(:id => person.id).where("readers.id = 1 or 1=1").references(:readers).includes(:posts).to_a.first
person = Person.create!(first_name: "Gaga")
person = Person.where(id: person.id).where("readers.id = 1 or 1=1").references(:readers).includes(:posts).to_a.first
assert person.posts.loaded?, "person.posts should be loaded"
assert_equal [], person.posts
@ -1101,7 +1101,7 @@ def test_explicitly_joining_join_table
end
def test_has_many_through_with_polymorphic_source
post = tags(:general).tagged_posts.create! :title => "foo", :body => "bar"
post = tags(:general).tagged_posts.create! title: "foo", body: "bar"
assert_equal [tags(:general)], post.reload.tags
end
@ -1148,9 +1148,9 @@ def test_insert_records_via_has_many_through_association_with_scope
end
def test_has_many_through_unscope_default_scope
post = Post.create!(:title => "Beaches", :body => "I like beaches!")
Reader.create! :person => people(:david), :post => post
LazyReader.create! :person => people(:susan), :post => post
post = Post.create!(title: "Beaches", body: "I like beaches!")
Reader.create! person: people(:david), post: post
LazyReader.create! person: people(:susan), post: post
assert_equal 2, post.people.to_a.size
assert_equal 1, post.lazy_people.to_a.size

@ -36,13 +36,13 @@ def test_has_one_cache_nils
assert_queries(1) { assert_nil firm.account }
assert_queries(0) { assert_nil firm.account }
firms = Firm.all.merge!(:includes => :account).to_a
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.all.merge!(: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
@ -102,7 +102,7 @@ def test_natural_assignment_to_nil
def test_nullification_on_association_change
firm = companies(:rails_core)
old_account_id = firm.account.id
firm.account = Account.new(:credit_limit => 5)
firm.account = Account.new(credit_limit: 5)
# account is dependent with nullify, therefore its firm_id should be nil
assert_nil Account.find(old_account_id).firm_id
end
@ -125,12 +125,12 @@ def test_natural_assignment_to_nil_after_destroy
end
def test_association_change_calls_delete
companies(:first_firm).deletable_account = Account.new(:credit_limit => 5)
companies(:first_firm).deletable_account = Account.new(credit_limit: 5)
assert_equal [], Account.destroyed_account_ids[companies(:first_firm).id]
end
def test_association_change_calls_destroy
companies(:first_firm).account = Account.new(:credit_limit => 5)
companies(:first_firm).account = Account.new(credit_limit: 5)
assert_equal [companies(:first_firm).id], Account.destroyed_account_ids[companies(:first_firm).id]
end
@ -170,19 +170,19 @@ def test_exclusive_dependence
end
def test_dependence_with_nil_associate
firm = DependentFirm.new(:name => "nullify")
firm = DependentFirm.new(name: "nullify")
firm.save!
assert_nothing_raised { firm.destroy }
end
def test_restrict_with_exception
firm = RestrictedWithExceptionFirm.create!(:name => "restrict")
firm.create_account(:credit_limit => 10)
firm = RestrictedWithExceptionFirm.create!(name: "restrict")
firm.create_account(credit_limit: 10)
assert_not_nil firm.account
assert_raise(ActiveRecord::DeleteRestrictionError) { firm.destroy }
assert RestrictedWithExceptionFirm.exists?(:name => "restrict")
assert RestrictedWithExceptionFirm.exists?(name: "restrict")
assert firm.account.present?
end
@ -206,8 +206,8 @@ def test_restrict_with_error_is_deprecated_using_key_one
end
def test_restrict_with_error
firm = RestrictedWithErrorFirm.create!(:name => "restrict")
firm.create_account(:credit_limit => 10)
firm = RestrictedWithErrorFirm.create!(name: "restrict")
firm.create_account(credit_limit: 10)
assert_not_nil firm.account
@ -215,7 +215,7 @@ def test_restrict_with_error
assert !firm.errors.empty?
assert_equal "Cannot delete record because a dependent account exists", firm.errors[:base].first
assert RestrictedWithErrorFirm.exists?(:name => "restrict")
assert RestrictedWithErrorFirm.exists?(name: "restrict")
assert firm.account.present?
end
@ -260,24 +260,24 @@ def test_building_the_associated_object_with_implicit_sti_base_class
def test_building_the_associated_object_with_explicit_sti_base_class
firm = DependentFirm.new
company = firm.build_company(:type => "Company")
company = firm.build_company(type: "Company")
assert_kind_of Company, company, "Expected #{company.class} to be a Company"
end
def test_building_the_associated_object_with_sti_subclass
firm = DependentFirm.new
company = firm.build_company(:type => "Client")
company = firm.build_company(type: "Client")
assert_kind_of Client, company, "Expected #{company.class} to be a Client"
end
def test_building_the_associated_object_with_an_invalid_type
firm = DependentFirm.new
assert_raise(ActiveRecord::SubclassNotFound) { firm.build_company(:type => "Invalid") }
assert_raise(ActiveRecord::SubclassNotFound) { firm.build_company(type: "Invalid") }
end
def test_building_the_associated_object_with_an_unrelated_type
firm = DependentFirm.new
assert_raise(ActiveRecord::SubclassNotFound) { firm.build_company(:type => "Account") }
assert_raise(ActiveRecord::SubclassNotFound) { firm.build_company(type: "Account") }
end
def test_build_and_create_should_not_happen_within_scope
@ -295,19 +295,19 @@ def test_build_and_create_should_not_happen_within_scope
end
def test_create_association
firm = Firm.create(:name => "GlobalMegaCorp")
account = firm.create_account(:credit_limit => 1000)
firm = Firm.create(name: "GlobalMegaCorp")
account = firm.create_account(credit_limit: 1000)
assert_equal account, firm.reload.account
end
def test_create_association_with_bang
firm = Firm.create(:name => "GlobalMegaCorp")
account = firm.create_account!(:credit_limit => 1000)
firm = Firm.create(name: "GlobalMegaCorp")
account = firm.create_account!(credit_limit: 1000)
assert_equal account, firm.reload.account
end
def test_create_association_with_bang_failing
firm = Firm.create(:name => "GlobalMegaCorp")
firm = Firm.create(name: "GlobalMegaCorp")
assert_raise ActiveRecord::RecordInvalid do
firm.create_account!
end
@ -365,7 +365,7 @@ def test_dependence_with_missing_association_and_nullify
def test_finding_with_interpolated_condition
firm = Firm.first
superior = firm.clients.create(:name => "SuperiorCo")
superior = firm.clients.create(name: "SuperiorCo")
superior.rating = 10
superior.save
assert_equal 10, firm.clients_with_interpolated_conditions.first.rating
@ -382,7 +382,7 @@ def test_assignment_before_child_saved
end
def test_save_still_works_after_accessing_nil_has_one
jp = Company.new :name => "Jaded Pixel"
jp = Company.new name: "Jaded Pixel"
jp.dummy_account.nil?
assert_nothing_raised do
@ -411,14 +411,14 @@ def test_save_of_record_with_loaded_has_one
assert_nothing_raised do
Firm.find(@firm.id).save!
Firm.all.merge!(: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.all.merge!(:includes => :account).find(@firm.id).save!
Firm.all.merge!(includes: :account).find(@firm.id).save!
end
end
@ -435,7 +435,7 @@ def test_create_respects_hash_condition
end
def test_attributes_are_being_set_when_initialized_from_has_one_association_with_where_clause
new_account = companies(:first_firm).build_account(:firm_name => "Account")
new_account = companies(:first_firm).build_account(firm_name: "Account")
assert_equal new_account.firm_name, "Account"
end
@ -505,60 +505,60 @@ def test_replacement_failure_due_to_new_record_should_raise_error
end
def test_association_keys_bypass_attribute_protection
car = Car.create(:name => "honda")
car = Car.create(name: "honda")
bulb = car.build_bulb
assert_equal car.id, bulb.car_id
bulb = car.build_bulb :car_id => car.id + 1
bulb = car.build_bulb car_id: car.id + 1
assert_equal car.id, bulb.car_id
bulb = car.create_bulb
assert_equal car.id, bulb.car_id
bulb = car.create_bulb :car_id => car.id + 1
bulb = car.create_bulb car_id: car.id + 1
assert_equal car.id, bulb.car_id
end
def test_association_protect_foreign_key
pirate = Pirate.create!(:catchphrase => "Don' botharrr talkin' like one, savvy?")
pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?")
ship = pirate.build_ship
assert_equal pirate.id, ship.pirate_id
ship = pirate.build_ship :pirate_id => pirate.id + 1
ship = pirate.build_ship pirate_id: pirate.id + 1
assert_equal pirate.id, ship.pirate_id
ship = pirate.create_ship
assert_equal pirate.id, ship.pirate_id
ship = pirate.create_ship :pirate_id => pirate.id + 1
ship = pirate.create_ship pirate_id: pirate.id + 1
assert_equal pirate.id, ship.pirate_id
end
def test_build_with_block
car = Car.create(:name => "honda")
car = Car.create(name: "honda")
bulb = car.build_bulb{ |b| b.color = "Red" }
assert_equal "RED!", bulb.color
end
def test_create_with_block
car = Car.create(:name => "honda")
car = Car.create(name: "honda")
bulb = car.create_bulb{ |b| b.color = "Red" }
assert_equal "RED!", bulb.color
end
def test_create_bang_with_block
car = Car.create(:name => "honda")
car = Car.create(name: "honda")
bulb = car.create_bulb!{ |b| b.color = "Red" }
assert_equal "RED!", bulb.color
end
def test_association_attributes_are_available_to_after_initialize
car = Car.create(:name => "honda")
car = Car.create(name: "honda")
bulb = car.create_bulb
assert_equal car.id, bulb.attributes_after_initialize["car_id"]
@ -635,7 +635,7 @@ def test_has_one_relationship_cannot_have_a_counter_cache
end
def test_with_polymorphic_has_one_with_custom_columns_name
post = Post.create! :title => "foo", :body => "bar"
post = Post.create! title: "foo", body: "bar"
image = Image.create!
post.main_image = image

@ -34,14 +34,14 @@ def test_has_one_through_with_has_one
end
def test_creating_association_creates_through_record
new_member = Member.create(:name => "Chris")
new_member.club = Club.create(:name => "LRUG")
new_member = Member.create(name: "Chris")
new_member.club = Club.create(name: "LRUG")
assert_not_nil new_member.current_membership
assert_not_nil new_member.club
end
def test_creating_association_builds_through_record_for_new
new_member = Member.new(:name => "Jane")
new_member = Member.new(name: "Jane")
new_member.club = clubs(:moustache_club)
assert new_member.current_membership
assert_equal clubs(:moustache_club), new_member.current_membership.club
@ -65,7 +65,7 @@ def test_creating_association_sets_both_parent_ids_for_new
end
def test_replace_target_record
new_club = Club.create(:name => "Marx Bros")
new_club = Club.create(name: "Marx Bros")
@member.club = new_club
@member.reload
assert_equal new_club, @member.club
@ -73,7 +73,7 @@ def test_replace_target_record
def test_replacing_target_record_deletes_old_association
assert_no_difference "Membership.count" do
new_club = Club.create(:name => "Bananarama")
new_club = Club.create(name: "Bananarama")
@member.club = new_club
@member.reload
end
@ -92,7 +92,7 @@ def test_has_one_through_polymorphic
def test_has_one_through_eager_loading
members = assert_queries(3) do #base table, through table, clubs table
Member.all.merge!(:includes => :club, :where => ["name = ?", "Groucho Marx"]).to_a
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}
@ -100,7 +100,7 @@ def test_has_one_through_eager_loading
def test_has_one_through_eager_loading_through_polymorphic
members = assert_queries(3) do #base table, through table, clubs table
Member.all.merge!(:includes => :sponsor_club, :where => ["name = ?", "Groucho Marx"]).to_a
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}
@ -108,14 +108,14 @@ def test_has_one_through_eager_loading_through_polymorphic
def test_has_one_through_with_conditions_eager_loading
# conditions on the through table
assert_equal clubs(:moustache_club), Member.all.merge!(:includes => :favourite_club).find(@member.id).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
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.all.merge!(:includes => :hairy_club).find(@member.id).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
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
@ -123,14 +123,14 @@ def test_has_one_through_polymorphic_with_source_type
end
def test_eager_has_one_through_polymorphic_with_source_type
clubs = Club.all.merge!(:includes => :sponsored_member, :where => ["name = ?","Moustache and Eyebrow Fancier Club"]).to_a
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.all.merge!(:includes => :club, :where => ["members.name = ?", "Groucho Marx"], :order => "clubs.name").to_a #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}
@ -138,16 +138,16 @@ def test_has_one_through_nonpreload_eagerloading
def test_has_one_through_nonpreload_eager_loading_through_polymorphic
members = assert_queries(1) do
Member.all.merge!(:includes => :sponsor_club, :where => ["members.name = ?", "Groucho Marx"], :order => "clubs.name").to_a #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}
end
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!
Sponsor.new(sponsor_club: clubs(:crazy_club), sponsorable: members(:groucho)).save!
members = assert_queries(1) do
Member.all.merge!(:includes => :sponsor_club, :where => ["members.name = ?", "Groucho Marx"], :order => "clubs.name DESC").to_a #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 }
@ -159,8 +159,8 @@ def test_uninitialized_has_one_through_should_return_nil_for_unsaved_record
end
def test_assigning_association_correctly_assigns_target
new_member = Member.create(:name => "Chris")
new_member.club = new_club = Club.create(:name => "LRUG")
new_member = Member.create(name: "Chris")
new_member.club = new_club = Club.create(name: "LRUG")
assert_equal new_club, new_member.association(:club).target
end
@ -177,7 +177,7 @@ def test_has_one_through_proxy_should_respond_to_private_methods_via_send
def test_assigning_to_has_one_through_preserves_decorated_join_record
@organization = organizations(:nsa)
assert_difference "MemberDetail.count", 1 do
@member_detail = MemberDetail.new(:extra_data => "Extra")
@member_detail = MemberDetail.new(extra_data: "Extra")
@member.member_detail = @member_detail
@member.organization = @organization
end
@ -191,7 +191,7 @@ def test_reassigning_has_one_through
@new_organization = organizations(:discordians)
assert_difference "MemberDetail.count", 1 do
@member_detail = MemberDetail.new(:extra_data => "Extra")
@member_detail = MemberDetail.new(extra_data: "Extra")
@member.member_detail = @member_detail
@member.organization = @organization
end
@ -217,7 +217,7 @@ def test_preloading_has_one_through_on_belongs_to
@member.member_detail = @member_detail
@member.organization = @organization
@member_details = assert_queries(3) do
MemberDetail.all.merge!(:includes => :member_type).to_a
MemberDetail.all.merge!(includes: :member_type).to_a
end
@new_detail = @member_details[0]
assert @new_detail.send(:association, :member_type).loaded?
@ -230,19 +230,19 @@ def test_save_of_record_with_loaded_has_one_through
assert_nothing_raised do
Club.find(@club.id).save!
Club.all.merge!(: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.all.merge!(:includes => :sponsored_member).find(@club.id).save!
Club.all.merge!(includes: :sponsored_member).find(@club.id).save!
end
end
def test_through_belongs_to_after_destroy
@member_detail = MemberDetail.new(:extra_data => "Extra")
@member_detail = MemberDetail.new(extra_data: "Extra")
@member.member_detail = @member_detail
@member.save!

@ -20,7 +20,7 @@ def test_construct_finder_sql_applies_aliases_tables_on_association_conditions
def test_construct_finder_sql_does_not_table_name_collide_on_duplicate_associations
assert_nothing_raised do
sql = Person.joins(:agents => {:agents => :agents}).joins(:agents => {:agents => {:primary_contact => :agents}}).to_sql
sql = Person.joins(agents: {agents: :agents}).joins(agents: {agents: {primary_contact: :agents}}).to_sql
assert_match(/agents_people_4/i, sql)
end
end
@ -47,7 +47,7 @@ def test_join_association_conditions_support_string_and_arel_expressions
end
def test_join_conditions_allow_nil_associations
authors = Author.includes(:essays).where(:essays => {:id => nil})
authors = Author.includes(:essays).where(essays: {id: nil})
assert_equal 2, authors.count
end
@ -92,7 +92,7 @@ def test_calculate_honors_implicit_inner_joins_and_distinct_and_conditions
end
def test_find_with_sti_join
scope = Post.joins(:special_comments).where(:id => posts(:sti_comments).id)
scope = Post.joins(:special_comments).where(id: posts(:sti_comments).id)
# The join should match SpecialComment and its subclasses only
assert scope.where("comments.type" => "Comment").empty?
@ -102,12 +102,12 @@ def test_find_with_sti_join
def test_find_with_conditions_on_reflection
assert !posts(:welcome).comments.empty?
assert Post.joins(:nonexistent_comments).where(:id => posts(:welcome).id).empty? # [sic!]
assert Post.joins(:nonexistent_comments).where(id: posts(:welcome).id).empty? # [sic!]
end
def test_find_with_conditions_on_through_reflection
assert !posts(:welcome).tags.empty?
assert Post.joins(:misc_tags).where(:id => posts(:welcome).id).empty?
assert Post.joins(:misc_tags).where(id: posts(:welcome).id).empty?
end
test "the default scope of the target is applied when joining associations" do

@ -131,15 +131,15 @@ def test_polymorphic_relationships_should_still_not_have_inverses_when_non_polym
class InverseAssociationTests < ActiveRecord::TestCase
def test_should_allow_for_inverse_of_options_in_associations
assert_nothing_raised do
Class.new(ActiveRecord::Base).has_many(:wheels, :inverse_of => :car)
Class.new(ActiveRecord::Base).has_many(:wheels, inverse_of: :car)
end
assert_nothing_raised do
Class.new(ActiveRecord::Base).has_one(:engine, :inverse_of => :car)
Class.new(ActiveRecord::Base).has_one(:engine, inverse_of: :car)
end
assert_nothing_raised do
Class.new(ActiveRecord::Base).belongs_to(:car, :inverse_of => :driver)
Class.new(ActiveRecord::Base).belongs_to(:car, inverse_of: :driver)
end
end
@ -228,7 +228,7 @@ def test_parent_instance_should_be_shared_with_child_on_find
def test_parent_instance_should_be_shared_with_eager_loaded_child_on_find
m = Man.all.merge!(: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"
@ -236,7 +236,7 @@ def test_parent_instance_should_be_shared_with_eager_loaded_child_on_find
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.all.merge!(: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"
@ -247,7 +247,7 @@ def test_parent_instance_should_be_shared_with_eager_loaded_child_on_find
def test_parent_instance_should_be_shared_with_newly_built_child
m = Man.first
f = m.build_face(:description => "haunted")
f = m.build_face(description: "haunted")
assert_not_nil f.man
assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
m.name = "Bongo"
@ -258,7 +258,7 @@ def test_parent_instance_should_be_shared_with_newly_built_child
def test_parent_instance_should_be_shared_with_newly_created_child
m = Man.first
f = m.create_face(:description => "haunted")
f = m.create_face(description: "haunted")
assert_not_nil f.man
assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
m.name = "Bongo"
@ -269,7 +269,7 @@ def test_parent_instance_should_be_shared_with_newly_created_child
def test_parent_instance_should_be_shared_with_newly_created_child_via_bang_method
m = Man.first
f = m.create_face!(:description => "haunted")
f = m.create_face!(description: "haunted")
assert_not_nil f.man
assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
m.name = "Bongo"
@ -280,7 +280,7 @@ def test_parent_instance_should_be_shared_with_newly_created_child_via_bang_meth
def test_parent_instance_should_be_shared_with_replaced_via_accessor_child
m = Man.first
f = Face.new(:description => "haunted")
f = Face.new(description: "haunted")
m.face = f
assert_not_nil f.man
assert_equal m.name, f.man.name, "Name of man should be the same before changes to parent instance"
@ -311,7 +311,7 @@ def test_parent_instance_should_be_shared_with_every_child_on_find
end
def test_parent_instance_should_be_shared_with_eager_loaded_children
m = Man.all.merge!(: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"
@ -321,7 +321,7 @@ def test_parent_instance_should_be_shared_with_eager_loaded_children
assert_equal m.name, i.man.name, "Name of man should be the same after changes to child-owned instance"
end
m = Man.all.merge!(: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"
@ -346,7 +346,7 @@ def test_parent_instance_should_be_shared_with_newly_block_style_built_child
def test_parent_instance_should_be_shared_with_newly_created_via_bang_method_child
m = Man.first
i = m.interests.create!(:topic => "Industrial Revolution Re-enactment")
i = m.interests.create!(topic: "Industrial Revolution Re-enactment")
assert_not_nil i.man
assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
m.name = "Bongo"
@ -385,7 +385,7 @@ def test_parent_instance_should_be_shared_within_build_block_of_new_child
def test_parent_instance_should_be_shared_with_poked_in_child
m = men(:gordon)
i = Interest.create(:topic => "Industrial Revolution Re-enactment")
i = Interest.create(topic: "Industrial Revolution Re-enactment")
m.interests << i
assert_not_nil i.man
assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
@ -397,7 +397,7 @@ def test_parent_instance_should_be_shared_with_poked_in_child
def test_parent_instance_should_be_shared_with_replaced_via_accessor_children
m = Man.first
i = Interest.new(:topic => "Industrial Revolution Re-enactment")
i = Interest.new(topic: "Industrial Revolution Re-enactment")
m.interests = [i]
assert_not_nil i.man
assert_equal m.name, i.man.name, "Name of man should be the same before changes to parent instance"
@ -485,7 +485,7 @@ def test_trying_to_use_inverses_that_dont_exist_should_raise_an_error
def test_child_instance_should_point_to_parent_without_saving
man = Man.new
i = Interest.create(:topic => "Industrial Revolution Re-enactment")
i = Interest.create(topic: "Industrial Revolution Re-enactment")
man.interests << i
assert_not_nil i.man
@ -511,7 +511,7 @@ def test_child_instance_should_be_shared_with_parent_on_find
end
def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find
f = Face.all.merge!(: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"
@ -519,7 +519,7 @@ def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find
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.all.merge!(: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"
@ -530,7 +530,7 @@ def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find
def test_child_instance_should_be_shared_with_newly_built_parent
f = faces(:trusting)
m = f.build_man(:name => "Charles")
m = f.build_man(name: "Charles")
assert_not_nil m.face
assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
f.description = "gormless"
@ -541,7 +541,7 @@ def test_child_instance_should_be_shared_with_newly_built_parent
def test_child_instance_should_be_shared_with_newly_created_parent
f = faces(:trusting)
m = f.create_man(:name => "Charles")
m = f.create_man(name: "Charles")
assert_not_nil m.face
assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
f.description = "gormless"
@ -565,7 +565,7 @@ def test_should_not_try_to_set_inverse_instances_when_the_inverse_is_a_has_many
def test_child_instance_should_be_shared_with_replaced_via_accessor_parent
f = Face.first
m = Man.new(:name => "Charles")
m = Man.new(name: "Charles")
f.man = m
assert_not_nil m.face
assert_equal f.description, m.face.description, "Description of face should be the same before changes to child instance"
@ -584,7 +584,7 @@ class InversePolymorphicBelongsToTests < ActiveRecord::TestCase
fixtures :men, :faces, :interests
def test_child_instance_should_be_shared_with_parent_on_find
f = Face.all.merge!(: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"
@ -594,7 +594,7 @@ def test_child_instance_should_be_shared_with_parent_on_find
end
def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find
f = Face.all.merge!(: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"
@ -602,7 +602,7 @@ def test_eager_loaded_child_instance_should_be_shared_with_parent_on_find
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.all.merge!(: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"
@ -698,8 +698,8 @@ def test_that_we_can_load_associations_that_have_the_same_reciprocal_name_from_d
def test_that_we_can_create_associations_that_have_the_same_reciprocal_name_from_different_models
assert_nothing_raised do
i = Interest.first
i.build_zine(:title => "Get Some in Winter! 2008")
i.build_man(:name => "Gordon")
i.build_zine(title: "Get Some in Winter! 2008")
i.build_man(name: "Gordon")
i.save!
end
end

@ -97,10 +97,10 @@ def test_polymorphic_has_many_going_through_join_model_with_custom_foreign_key
end
def test_polymorphic_has_many_create_model_with_inheritance_and_custom_base_class
post = SubStiPost.create :title => "SubStiPost", :body => "SubStiPost body"
post = SubStiPost.create title: "SubStiPost", body: "SubStiPost body"
assert_instance_of SubStiPost, post
tagging = tags(:misc).taggings.create(:taggable => post)
tagging = tags(:misc).taggings.create(taggable: post)
assert_equal "SubStiPost", tagging.taggable_type
end
@ -116,12 +116,12 @@ def test_polymorphic_has_many_create_model_with_inheritance
post = posts(:thinking)
assert_instance_of SpecialPost, post
tagging = tags(:misc).taggings.create(:taggable => post)
tagging = tags(:misc).taggings.create(taggable: post)
assert_equal "Post", tagging.taggable_type
end
def test_polymorphic_has_one_create_model_with_inheritance
tagging = tags(:misc).create_tagging(:taggable => posts(:thinking))
tagging = tags(:misc).create_tagging(taggable: posts(:thinking))
assert_equal "Post", tagging.taggable_type
end
@ -142,7 +142,7 @@ def test_set_polymorphic_has_one
def test_set_polymorphic_has_one_on_new_record
tagging = tags(:misc).taggings.create
post = Post.new :title => "foo", :body => "bar"
post = Post.new title: "foo", body: "bar"
post.tagging = tagging
post.save!
@ -153,21 +153,21 @@ def test_set_polymorphic_has_one_on_new_record
def test_create_polymorphic_has_many_with_scope
old_count = posts(:welcome).taggings.count
tagging = posts(:welcome).taggings.create(:tag => tags(:misc))
tagging = posts(:welcome).taggings.create(tag: tags(:misc))
assert_equal "Post", tagging.taggable_type
assert_equal old_count+1, posts(:welcome).taggings.count
end
def test_create_bang_polymorphic_with_has_many_scope
old_count = posts(:welcome).taggings.count
tagging = posts(:welcome).taggings.create!(:tag => tags(:misc))
tagging = posts(:welcome).taggings.create!(tag: tags(:misc))
assert_equal "Post", tagging.taggable_type
assert_equal old_count+1, posts(:welcome).taggings.count
end
def test_create_polymorphic_has_one_with_scope
old_count = Tagging.count
tagging = posts(:welcome).create_tagging(:tag => tags(:misc))
tagging = posts(:welcome).create_tagging(tag: tags(:misc))
assert_equal "Post", tagging.taggable_type
assert_equal old_count+1, Tagging.count
end
@ -235,15 +235,15 @@ def test_has_many_with_piggyback
def test_create_through_has_many_with_piggyback
category = categories(:sti_test)
ernie = category.authors_with_select.create(:name => "Ernie")
ernie = category.authors_with_select.create(name: "Ernie")
assert_nothing_raised do
assert_equal ernie, category.authors_with_select.detect {|a| a.name == "Ernie"}
end
end
def test_include_has_many_through
posts = Post.all.merge!(:order => "posts.id").to_a
posts_with_authors = Post.all.merge!(:includes => :authors, :order => "posts.id").to_a
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 }
@ -267,8 +267,8 @@ def test_include_polymorphic_has_one_defined_in_abstract_parent
end
def test_include_polymorphic_has_many_through
posts = Post.all.merge!(:order => "posts.id").to_a
posts_with_tags = Post.all.merge!(:includes => :tags, :order => "posts.id").to_a
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 }
@ -276,8 +276,8 @@ def test_include_polymorphic_has_many_through
end
def test_include_polymorphic_has_many
posts = Post.all.merge!(:order => "posts.id").to_a
posts_with_taggings = Post.all.merge!(:includes => :taggings, :order => "posts.id").to_a
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 }
@ -329,7 +329,7 @@ def test_has_many_through_with_custom_primary_key_on_has_many_source
def test_belongs_to_polymorphic_with_counter_cache
assert_equal 1, posts(:welcome)[:tags_count]
tagging = posts(:welcome).taggings.create(:tag => tags(:general))
tagging = posts(:welcome).taggings.create(tag: tags(:general))
assert_equal 2, posts(:welcome, :reload)[:tags_count]
tagging.destroy
assert_equal 1, posts(:welcome, :reload)[:tags_count]
@ -365,13 +365,13 @@ def test_has_many_polymorphic_with_source_type
def test_has_many_polymorphic_associations_merges_through_scope
Tag.has_many :null_taggings, -> { none }, class_name: :Tagging
Tag.has_many :null_tagged_posts, :through => :null_taggings, :source => "taggable", :source_type => "Post"
Tag.has_many :null_tagged_posts, through: :null_taggings, source: "taggable", source_type: "Post"
assert_equal [], tags(:general).null_tagged_posts
refute_equal [], tags(:general).tagged_posts
end
def test_eager_has_many_polymorphic_with_source_type
tag_with_include = Tag.all.merge!(: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
@ -393,7 +393,7 @@ def test_has_many_through_has_many_find_first
end
def test_has_many_through_has_many_find_conditions
options = { :where => "comments.#{QUOTED_TYPE}='SpecialComment'", :order => "comments.id" }
options = { where: "comments.#{QUOTED_TYPE}='SpecialComment'", order: "comments.id" }
assert_equal comments(:does_it_hurt), authors(:david).comments.merge(options).first
end
@ -418,7 +418,7 @@ def test_include_has_many_through_polymorphic_has_many
end
def test_eager_load_has_many_through_has_many
author = Author.all.merge!(: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)
@ -426,7 +426,7 @@ def test_eager_load_has_many_through_has_many
end
def test_eager_load_has_many_through_has_many_with_conditions
post = Post.all.merge!(:includes => :invalid_tags).first
post = Post.all.merge!(includes: :invalid_tags).first
assert_no_queries do
post.invalid_tags
end
@ -434,8 +434,8 @@ def test_eager_load_has_many_through_has_many_with_conditions
def test_eager_belongs_to_and_has_one_not_singularized
assert_nothing_raised do
Author.all.merge!(:includes => :author_address).first
AuthorAddress.all.merge!(:includes => :author).first
Author.all.merge!(includes: :author_address).first
AuthorAddress.all.merge!(includes: :author).first
end
end
@ -445,8 +445,8 @@ def test_self_referential_has_many_through
end
def test_add_to_self_referential_has_many_through
new_author = Author.create(:name => "Bob")
authors(:david).author_favorites.create :favorite_author => new_author
new_author = Author.create(name: "Bob")
authors(:david).author_favorites.create favorite_author: new_author
assert_equal new_author, authors(:david).reload.favorite_authors.first
end
@ -462,7 +462,7 @@ def test_has_many_through_uses_correct_attributes
def test_associating_unsaved_records_with_has_many_through
saved_post = posts(:thinking)
new_tag = Tag.new(:name => "new")
new_tag = Tag.new(name: "new")
saved_post.tags << new_tag
assert new_tag.persisted? #consistent with habtm!
@ -473,7 +473,7 @@ def test_associating_unsaved_records_with_has_many_through
assert saved_post.reload.tags.reload.include?(new_tag)
new_post = Post.new(:title => "Association replacement works!", :body => "You best believe it.")
new_post = Post.new(title: "Association replacement works!", body: "You best believe it.")
saved_tag = tags(:general)
new_post.tags << saved_tag
@ -491,7 +491,7 @@ def test_associating_unsaved_records_with_has_many_through
def test_create_associate_when_adding_to_has_many_through
count = posts(:thinking).tags.count
push = Tag.create!(:name => "pushme")
push = Tag.create!(name: "pushme")
post_thinking = posts(:thinking)
assert_nothing_raised { post_thinking.tags << push }
assert_nil( wrong = post_thinking.tags.detect { |t| t.class != Tag },
@ -501,7 +501,7 @@ def test_create_associate_when_adding_to_has_many_through
assert_equal(count + 1, post_thinking.reload.tags.size)
assert_equal(count + 1, post_thinking.tags.reload.size)
assert_kind_of Tag, post_thinking.tags.create!(:name => "foo")
assert_kind_of Tag, post_thinking.tags.create!(name: "foo")
assert_nil( wrong = post_thinking.tags.detect { |t| t.class != Tag },
message = "Expected a Tag in tags collection, got #{wrong.class}.")
assert_nil( wrong = post_thinking.taggings.detect { |t| t.class != Tagging },
@ -509,7 +509,7 @@ def test_create_associate_when_adding_to_has_many_through
assert_equal(count + 2, post_thinking.reload.tags.size)
assert_equal(count + 2, post_thinking.tags.reload.size)
assert_nothing_raised { post_thinking.tags.concat(Tag.create!(:name => "abc"), Tag.create!(:name => "def")) }
assert_nothing_raised { post_thinking.tags.concat(Tag.create!(name: "abc"), Tag.create!(name: "def")) }
assert_nil( wrong = post_thinking.tags.detect { |t| t.class != Tag },
message = "Expected a Tag in tags collection, got #{wrong.class}.")
assert_nil( wrong = post_thinking.taggings.detect { |t| t.class != Tagging },
@ -550,7 +550,7 @@ def test_adding_to_has_many_through_should_return_self
def test_delete_associate_when_deleting_from_has_many_through_with_nonstandard_id
count = books(:awdr).references.count
references_before = books(:awdr).references
book = Book.create!(:name => "Getting Real")
book = Book.create!(name: "Getting Real")
book_awdr = books(:awdr)
book_awdr.references << book
assert_equal(count + 1, book_awdr.references.reload.size)
@ -564,7 +564,7 @@ def test_delete_associate_when_deleting_from_has_many_through_with_nonstandard_i
def test_delete_associate_when_deleting_from_has_many_through
count = posts(:thinking).tags.count
tags_before = posts(:thinking).tags.sort
tag = Tag.create!(:name => "doomed")
tag = Tag.create!(name: "doomed")
post_thinking = posts(:thinking)
post_thinking.tags << tag
assert_equal(count + 1, post_thinking.taggings.reload.size)
@ -581,9 +581,9 @@ def test_delete_associate_when_deleting_from_has_many_through
def test_delete_associate_when_deleting_from_has_many_through_with_multiple_tags
count = posts(:thinking).tags.count
tags_before = posts(:thinking).tags.sort
doomed = Tag.create!(:name => "doomed")
doomed2 = Tag.create!(:name => "doomed2")
quaked = Tag.create!(:name => "quaked")
doomed = Tag.create!(name: "doomed")
doomed2 = Tag.create!(name: "doomed2")
quaked = Tag.create!(name: "quaked")
post_thinking = posts(:thinking)
post_thinking.tags << doomed << doomed2
assert_equal(count + 2, post_thinking.reload.tags.reload.size)
@ -642,7 +642,7 @@ def test_distinct_has_many_through_should_retain_order
def test_polymorphic_has_many
expected = taggings(:welcome_general)
p = Post.all.merge!(: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
@ -650,18 +650,18 @@ def test_polymorphic_has_many
def test_polymorphic_has_one
expected = posts(:welcome)
tagging = Tagging.all.merge!(: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.all.merge!(: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.all.merge!(:order => "posts.id").to_a
posts_with_tags = Post.all.merge!(:includes => :tags, :order => "posts.id").to_a
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 }
@ -669,7 +669,7 @@ def test_preload_polymorphic_has_many_through
end
def test_preload_polymorph_many_types
taggings = Tagging.all.merge!(:includes => :taggable, :where => ["taggable_type != ?", "FakeModel"]).to_a
taggings = Tagging.all.merge!(includes: :taggable, where: ["taggable_type != ?", "FakeModel"]).to_a
assert_no_queries do
taggings.first.taggable.id
taggings[1].taggable.id
@ -682,13 +682,13 @@ def test_preload_polymorph_many_types
def test_preload_nil_polymorphic_belongs_to
assert_nothing_raised do
Tagging.all.merge!(:includes => :taggable, :where => ["taggable_type IS NULL"]).to_a
Tagging.all.merge!(includes: :taggable, where: ["taggable_type IS NULL"]).to_a
end
end
def test_preload_polymorphic_has_many
posts = Post.all.merge!(:order => "posts.id").to_a
posts_with_taggings = Post.all.merge!(:includes => :taggings, :order => "posts.id").to_a
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 }
@ -696,7 +696,7 @@ def test_preload_polymorphic_has_many
end
def test_belongs_to_shared_parent
comments = Comment.all.merge!(:includes => :post, :where => "post_id = 1").to_a
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
@ -728,22 +728,22 @@ def test_has_many_through_include_checks_if_record_exists_if_target_not_loaded
def test_has_many_through_include_returns_false_for_non_matching_record_to_verify_scoping
david = authors(:david)
category = Category.create!(:name => "Not Associated")
category = Category.create!(name: "Not Associated")
assert ! david.categories.loaded?
assert ! david.categories.include?(category)
end
def test_has_many_through_goes_through_all_sti_classes
sub_sti_post = SubStiPost.create!(:title => "test", :body => "test", :author_id => 1)
new_comment = sub_sti_post.comments.create(:body => "test")
sub_sti_post = SubStiPost.create!(title: "test", body: "test", author_id: 1)
new_comment = sub_sti_post.comments.create(body: "test")
assert_equal [9, 10, new_comment.id], authors(:david).sti_post_comments.map(&:id).sort
end
def test_has_many_with_pluralize_table_names_false
aircraft = Aircraft.create!(:name => "Airbus 380")
engine = Engine.create!(:car_id => aircraft.id)
aircraft = Aircraft.create!(name: "Airbus 380")
engine = Engine.create!(car_id: aircraft.id)
assert_equal aircraft.engines, [engine]
end
@ -771,7 +771,7 @@ def find_post_with_dependency(post_id, association, association_name, dependency
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)
klass.send(association, association_name, as: :taggable, dependent: dependency)
klass.find(post_id)
end
end

@ -18,8 +18,8 @@ def test_construct_finder_sql_applies_aliases_tables_on_association_conditions
def test_construct_finder_sql_does_not_table_name_collide_on_duplicate_associations
assert_nothing_raised do
queries = capture_sql do
Person.left_outer_joins(:agents => {:agents => :agents})
.left_outer_joins(:agents => {:agents => {:primary_contact => :agents}}).to_a
Person.left_outer_joins(agents: {agents: :agents})
.left_outer_joins(agents: {agents: {primary_contact: :agents}}).to_a
end
assert queries.any? { |sql| /agents_people_4/i.match?(sql) }
end
@ -56,7 +56,7 @@ def test_join_conditions_added_to_join_clause
end
def test_find_with_sti_join
scope = Post.left_outer_joins(:special_comments).where(:id => posts(:sti_comments).id)
scope = Post.left_outer_joins(:special_comments).where(id: posts(:sti_comments).id)
# The join should match SpecialComment and its subclasses only
assert scope.where("comments.type" => "Comment").empty?

@ -443,7 +443,7 @@ def test_has_many_through_with_sti_on_through_reflection
assert_equal [ratings(:special_comment_rating), ratings(:sub_special_comment_rating)], ratings
# Ensure STI is respected in the join
scope = Post.joins(:special_comments_ratings).where(:id => posts(:sti_comments).id)
scope = Post.joins(:special_comments_ratings).where(id: posts(:sti_comments).id)
assert scope.where("comments.type" => "Comment").empty?
assert !scope.where("comments.type" => "SpecialComment").empty?
assert !scope.where("comments.type" => "SubSpecialComment").empty?
@ -453,7 +453,7 @@ def test_has_many_through_with_sti_on_nested_through_reflection
taggings = posts(:sti_comments).special_comments_ratings_taggings
assert_equal [taggings(:special_comment_rating)], taggings
scope = Post.joins(:special_comments_ratings_taggings).where(:id => posts(:sti_comments).id)
scope = Post.joins(:special_comments_ratings_taggings).where(id: posts(:sti_comments).id)
assert scope.where("comments.type" => "Comment").empty?
assert !scope.where("comments.type" => "SpecialComment").empty?
end

@ -25,32 +25,32 @@ class AssociationsTest < ActiveRecord::TestCase
:computers, :people, :readers, :authors, :author_favorites
def test_eager_loading_should_not_change_count_of_children
liquid = Liquid.create(:name => "salty")
molecule = liquid.molecules.create(:name => "molecule_1")
molecule.electrons.create(:name => "electron_1")
molecule.electrons.create(:name => "electron_2")
liquid = Liquid.create(name: "salty")
molecule = liquid.molecules.create(name: "molecule_1")
molecule.electrons.create(name: "electron_1")
molecule.electrons.create(name: "electron_2")
liquids = Liquid.includes(:molecules => :electrons).references(:molecules).where("molecules.id is not null")
liquids = Liquid.includes(molecules: :electrons).references(:molecules).where("molecules.id is not null")
assert_equal 1, liquids[0].molecules.length
end
def test_subselect
author = authors :david
favs = author.author_favorites
fav2 = author.author_favorites.where(:author => Author.where(id: author.id)).to_a
fav2 = author.author_favorites.where(author: Author.where(id: author.id)).to_a
assert_equal favs, fav2
end
def test_loading_the_association_target_should_keep_child_records_marked_for_destruction
ship = Ship.create!(:name => "The good ship Dollypop")
part = ship.parts.create!(:name => "Mast")
ship = Ship.create!(name: "The good ship Dollypop")
part = ship.parts.create!(name: "Mast")
part.mark_for_destruction
assert ship.parts[0].marked_for_destruction?
end
def test_loading_the_association_target_should_load_most_recent_attributes_for_child_records_marked_for_destruction
ship = Ship.create!(:name => "The good ship Dollypop")
part = ship.parts.create!(:name => "Mast")
ship = Ship.create!(name: "The good ship Dollypop")
part = ship.parts.create!(name: "Mast")
part.mark_for_destruction
ShipPart.find(part.id).update_columns(name: "Deck")
assert_equal "Deck", ship.parts[0].name
@ -58,21 +58,21 @@ def test_loading_the_association_target_should_load_most_recent_attributes_for_c
def test_include_with_order_works
assert_nothing_raised {Account.all.merge!(: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}
assert_nothing_raised {Account.all.merge!(order: :id, includes: :firm).first}
end
def test_bad_collection_keys
assert_raise(ArgumentError, "ActiveRecord should have barked on bad collection keys") do
Class.new(ActiveRecord::Base).has_many(:wheels, :name => "wheels")
Class.new(ActiveRecord::Base).has_many(:wheels, name: "wheels")
end
end
def test_should_construct_new_finder_sql_after_create
person = Person.new :first_name => "clark"
person = Person.new first_name: "clark"
assert_equal [], person.readers.to_a
person.save!
reader = Reader.create! :person => person, :post => Post.new(:title => "foo", :body => "bar")
reader = Reader.create! person: person, post: Post.new(title: "foo", body: "bar")
assert person.readers.find(reader.id)
end
@ -131,7 +131,7 @@ class AssociationProxyTest < ActiveRecord::TestCase
def test_push_does_not_load_target
david = authors(:david)
david.posts << (post = Post.new(:title => "New on Edge", :body => "More cool stuff!"))
david.posts << (post = Post.new(title: "New on Edge", body: "More cool stuff!"))
assert !david.posts.loaded?
assert david.posts.include?(post)
end
@ -147,7 +147,7 @@ def test_push_has_many_through_does_not_load_target
def test_push_followed_by_save_does_not_load_target
david = authors(:david)
david.posts << (post = Post.new(:title => "New on Edge", :body => "More cool stuff!"))
david.posts << (post = Post.new(title: "New on Edge", body: "More cool stuff!"))
assert !david.posts.loaded?
david.save
assert !david.posts.loaded?
@ -155,21 +155,21 @@ def test_push_followed_by_save_does_not_load_target
end
def test_push_does_not_lose_additions_to_new_record
josh = Author.new(:name => "Josh")
josh.posts << Post.new(:title => "New on Edge", :body => "More cool stuff!")
josh = Author.new(name: "Josh")
josh.posts << Post.new(title: "New on Edge", body: "More cool stuff!")
assert josh.posts.loaded?
assert_equal 1, josh.posts.size
end
def test_append_behaves_like_push
josh = Author.new(:name => "Josh")
josh.posts.append Post.new(:title => "New on Edge", :body => "More cool stuff!")
josh = Author.new(name: "Josh")
josh.posts.append Post.new(title: "New on Edge", body: "More cool stuff!")
assert josh.posts.loaded?
assert_equal 1, josh.posts.size
end
def test_prepend_is_not_defined
josh = Author.new(:name => "Josh")
josh = Author.new(name: "Josh")
assert_raises(NoMethodError) { josh.posts.prepend Post.new }
end
@ -190,24 +190,24 @@ def test_load_does_load_target
end
def test_inspect_does_not_reload_a_not_yet_loaded_target
andreas = Developer.new :name => "Andreas", :log => "new developer added"
andreas = Developer.new name: "Andreas", log: "new developer added"
assert !andreas.audit_logs.loaded?
assert_match(/message: "new developer added"/, andreas.audit_logs.inspect)
end
def test_save_on_parent_saves_children
developer = Developer.create :name => "Bryan", :salary => 50_000
developer = Developer.create name: "Bryan", salary: 50_000
assert_equal 1, developer.reload.audit_logs.size
end
def test_create_via_association_with_block
post = authors(:david).posts.create(:title => "New on Edge") {|p| p.body = "More cool stuff!"}
post = authors(:david).posts.create(title: "New on Edge") {|p| p.body = "More cool stuff!"}
assert_equal post.title, "New on Edge"
assert_equal post.body, "More cool stuff!"
end
def test_create_with_bang_via_association_with_block
post = authors(:david).posts.create!(:title => "New on Edge") {|p| p.body = "More cool stuff!"}
post = authors(:david).posts.create!(title: "New on Edge") {|p| p.body = "More cool stuff!"}
assert_equal post.title, "New on Edge"
assert_equal post.body, "More cool stuff!"
end
@ -272,18 +272,18 @@ class OverridingAssociationsTest < ActiveRecord::TestCase
class DifferentPerson < ActiveRecord::Base; end
class PeopleList < ActiveRecord::Base
has_and_belongs_to_many :has_and_belongs_to_many, :before_add => :enlist
has_many :has_many, :before_add => :enlist
has_and_belongs_to_many :has_and_belongs_to_many, before_add: :enlist
has_many :has_many, before_add: :enlist
belongs_to :belongs_to
has_one :has_one
end
class DifferentPeopleList < PeopleList
# Different association with the same name, callbacks should be omitted here.
has_and_belongs_to_many :has_and_belongs_to_many, :class_name => "DifferentPerson"
has_many :has_many, :class_name => "DifferentPerson"
belongs_to :belongs_to, :class_name => "DifferentPerson"
has_one :has_one, :class_name => "DifferentPerson"
has_and_belongs_to_many :has_and_belongs_to_many, class_name: "DifferentPerson"
has_many :has_many, class_name: "DifferentPerson"
belongs_to :belongs_to, class_name: "DifferentPerson"
has_one :has_one, class_name: "DifferentPerson"
end
def test_habtm_association_redefinition_callbacks_should_differ_and_not_inherited

@ -31,7 +31,7 @@ class TestAutosaveAssociationsInGeneral < ActiveRecord::TestCase
def test_autosave_validation
person = Class.new(ActiveRecord::Base) {
self.table_name = "people"
validate :should_be_cool, :on => :create
validate :should_be_cool, on: :create
def self.name; "Person"; end
private
@ -97,7 +97,7 @@ class TestDefaultAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCas
fixtures :companies, :accounts
def test_should_save_parent_but_not_invalid_child
firm = Firm.new(:name => "GlobalMegaCorp")
firm = Firm.new(name: "GlobalMegaCorp")
assert firm.valid?
firm.build_account_using_primary_key
@ -178,7 +178,7 @@ def test_assignment_before_either_saved
end
def test_not_resaved_when_unchanged
firm = Firm.all.merge!(:includes => :account).first
firm = Firm.all.merge!(includes: :account).first
firm.name += "-changed"
assert_queries(1) { firm.save! }
@ -196,7 +196,7 @@ def test_not_resaved_when_unchanged
end
def test_callbacks_firing_order_on_create
eye = Eye.create(:iris_attributes => {:color => "honey"})
eye = Eye.create(iris_attributes: {color: "honey"})
assert_equal [true, false], eye.after_create_callbacks_stack
end
@ -219,7 +219,7 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test
fixtures :companies, :posts, :tags, :taggings
def test_should_save_parent_but_not_invalid_child
client = Client.new(:name => "Joe (the Plumber)")
client = Client.new(name: "Joe (the Plumber)")
assert client.valid?
client.build_firm
@ -231,7 +231,7 @@ def test_should_save_parent_but_not_invalid_child
def test_save_fails_for_invalid_belongs_to
# Oracle saves empty string as NULL therefore :message changed to one space
assert log = AuditLog.create(:developer_id => 0, :message => " ")
assert log = AuditLog.create(developer_id: 0, message: " ")
log.developer = Developer.new
assert !log.developer.valid?
@ -242,7 +242,7 @@ def test_save_fails_for_invalid_belongs_to
def test_save_succeeds_for_invalid_belongs_to_with_validate_false
# Oracle saves empty string as NULL therefore :message changed to one space
assert log = AuditLog.create(:developer_id => 0, :message=> " ")
assert log = AuditLog.create(developer_id: 0, message: " ")
log.unvalidated_developer = Developer.new
assert !log.unvalidated_developer.valid?
@ -362,22 +362,22 @@ def test_store_association_in_two_relations_with_one_save_in_existing_object_wit
def test_store_association_with_a_polymorphic_relationship
num_tagging = Tagging.count
tags(:misc).create_tagging(:taggable => posts(:thinking))
tags(:misc).create_tagging(taggable: posts(:thinking))
assert_equal num_tagging + 1, Tagging.count
end
def test_build_and_then_save_parent_should_not_reload_target
client = Client.first
apple = client.build_firm(:name => "Apple")
apple = client.build_firm(name: "Apple")
client.save!
assert_no_queries { assert_equal apple, client.firm }
end
def test_validation_does_not_validate_stale_association_target
valid_developer = Developer.create!(:name => "Dude", :salary => 50_000)
valid_developer = Developer.create!(name: "Dude", salary: 50_000)
invalid_developer = Developer.new()
auditlog = AuditLog.new(:message => "foo")
auditlog = AuditLog.new(message: "foo")
auditlog.developer = invalid_developer
auditlog.developer_id = valid_developer.id
@ -589,7 +589,7 @@ def test_assign_ids
end
def test_assign_ids_for_through_a_belongs_to
post = Post.new(:title => "Assigning IDs works!", :body => "You heard it here first, folks!")
post = Post.new(title: "Assigning IDs works!", body: "You heard it here first, folks!")
post.person_ids = [people(:david).id, people(:michael).id]
post.save
post.reload
@ -727,8 +727,8 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
self.use_transactional_tests = false
setup do
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@ship = @pirate.create_ship(:name => "Nights Dirty Lightning")
@pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?")
@ship = @pirate.create_ship(name: "Nights Dirty Lightning")
end
teardown do
@ -858,8 +858,8 @@ def save(*args)
end
def test_should_save_changed_child_objects_if_parent_is_saved
@pirate = @ship.create_pirate(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@parrot = @pirate.parrots.create!(:name => "Posideons Killer")
@pirate = @ship.create_pirate(catchphrase: "Don' botharrr talkin' like one, savvy?")
@parrot = @pirate.parrots.create!(name: "Posideons Killer")
@parrot.name = "NewName"
@ship.save
@ -867,7 +867,7 @@ def test_should_save_changed_child_objects_if_parent_is_saved
end
def test_should_destroy_has_many_as_part_of_the_save_transaction_if_they_were_marked_for_destruction
2.times { |i| @pirate.birds.create!(:name => "birds_#{i}") }
2.times { |i| @pirate.birds.create!(name: "birds_#{i}") }
assert !@pirate.birds.any?(&:marked_for_destruction?)
@ -891,7 +891,7 @@ def test_should_not_resave_destroyed_association
end
def test_should_skip_validation_on_has_many_if_marked_for_destruction
2.times { |i| @pirate.birds.create!(:name => "birds_#{i}") }
2.times { |i| @pirate.birds.create!(name: "birds_#{i}") }
@pirate.birds.each { |bird| bird.name = "" }
assert !@pirate.valid?
@ -904,7 +904,7 @@ def test_should_skip_validation_on_has_many_if_marked_for_destruction
end
def test_should_skip_validation_on_has_many_if_destroyed
@pirate.birds.create!(:name => "birds_1")
@pirate.birds.create!(name: "birds_1")
@pirate.birds.each { |bird| bird.name = "" }
assert !@pirate.valid?
@ -914,7 +914,7 @@ def test_should_skip_validation_on_has_many_if_destroyed
end
def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_has_many
@pirate.birds.create!(:name => "birds_1")
@pirate.birds.create!(name: "birds_1")
@pirate.birds.each(&:mark_for_destruction)
assert @pirate.save
@ -924,7 +924,7 @@ def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_savi
end
def test_should_rollback_destructions_if_an_exception_occurred_while_saving_has_many
2.times { |i| @pirate.birds.create!(:name => "birds_#{i}") }
2.times { |i| @pirate.birds.create!(name: "birds_#{i}") }
before = @pirate.birds.map { |c| c.mark_for_destruction ; c }
# Stub the destroy method of the second child to raise an exception
@ -940,9 +940,9 @@ def destroy(*args)
end
def test_when_new_record_a_child_marked_for_destruction_should_not_affect_other_records_from_saving
@pirate = @ship.build_pirate(:catchphrase => "Arr' now I shall keep me eye on you matey!") # new record
@pirate = @ship.build_pirate(catchphrase: "Arr' now I shall keep me eye on you matey!") # new record
3.times { |i| @pirate.birds.build(:name => "birds_#{i}") }
3.times { |i| @pirate.birds.build(name: "birds_#{i}") }
@pirate.birds[1].mark_for_destruction
@pirate.save!
@ -968,8 +968,8 @@ def test_should_save_new_record_that_has_same_value_as_existing_record_marked_fo
define_method("test_should_run_add_callback_#{callback_type}s_for_has_many") do
association_name_with_callbacks = "birds_with_#{callback_type}_callbacks"
pirate = Pirate.new(:catchphrase => "Arr")
pirate.send(association_name_with_callbacks).build(:name => "Crowe the One-Eyed")
pirate = Pirate.new(catchphrase: "Arr")
pirate.send(association_name_with_callbacks).build(name: "Crowe the One-Eyed")
expected = [
"before_adding_#{callback_type}_bird_<new>",
@ -982,7 +982,7 @@ def test_should_save_new_record_that_has_same_value_as_existing_record_marked_fo
define_method("test_should_run_remove_callback_#{callback_type}s_for_has_many") do
association_name_with_callbacks = "birds_with_#{callback_type}_callbacks"
@pirate.send(association_name_with_callbacks).create!(:name => "Crowe the One-Eyed")
@pirate.send(association_name_with_callbacks).create!(name: "Crowe the One-Eyed")
@pirate.send(association_name_with_callbacks).each(&:mark_for_destruction)
child_id = @pirate.send(association_name_with_callbacks).first.id
@ -999,7 +999,7 @@ def test_should_save_new_record_that_has_same_value_as_existing_record_marked_fo
end
def test_should_destroy_habtm_as_part_of_the_save_transaction_if_they_were_marked_for_destruction
2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") }
2.times { |i| @pirate.parrots.create!(name: "parrots_#{i}") }
assert !@pirate.parrots.any?(&:marked_for_destruction?)
@pirate.parrots.each(&:mark_for_destruction)
@ -1015,7 +1015,7 @@ def test_should_destroy_habtm_as_part_of_the_save_transaction_if_they_were_marke
end
def test_should_skip_validation_on_habtm_if_marked_for_destruction
2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") }
2.times { |i| @pirate.parrots.create!(name: "parrots_#{i}") }
@pirate.parrots.each { |parrot| parrot.name = "" }
assert !@pirate.valid?
@ -1030,7 +1030,7 @@ def test_should_skip_validation_on_habtm_if_marked_for_destruction
end
def test_should_skip_validation_on_habtm_if_destroyed
@pirate.parrots.create!(:name => "parrots_1")
@pirate.parrots.create!(name: "parrots_1")
@pirate.parrots.each { |parrot| parrot.name = "" }
assert !@pirate.valid?
@ -1040,7 +1040,7 @@ def test_should_skip_validation_on_habtm_if_destroyed
end
def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_habtm
@pirate.parrots.create!(:name => "parrots_1")
@pirate.parrots.create!(name: "parrots_1")
@pirate.parrots.each(&:mark_for_destruction)
assert @pirate.save
@ -1053,7 +1053,7 @@ def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_savi
end
def test_should_rollback_destructions_if_an_exception_occurred_while_saving_habtm
2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") }
2.times { |i| @pirate.parrots.create!(name: "parrots_#{i}") }
before = @pirate.parrots.map { |c| c.mark_for_destruction ; c }
class << @pirate.association(:parrots)
@ -1072,8 +1072,8 @@ def destroy(*args)
define_method("test_should_run_add_callback_#{callback_type}s_for_habtm") do
association_name_with_callbacks = "parrots_with_#{callback_type}_callbacks"
pirate = Pirate.new(:catchphrase => "Arr")
pirate.send(association_name_with_callbacks).build(:name => "Crowe the One-Eyed")
pirate = Pirate.new(catchphrase: "Arr")
pirate.send(association_name_with_callbacks).build(name: "Crowe the One-Eyed")
expected = [
"before_adding_#{callback_type}_parrot_<new>",
@ -1086,7 +1086,7 @@ def destroy(*args)
define_method("test_should_run_remove_callback_#{callback_type}s_for_habtm") do
association_name_with_callbacks = "parrots_with_#{callback_type}_callbacks"
@pirate.send(association_name_with_callbacks).create!(:name => "Crowe the One-Eyed")
@pirate.send(association_name_with_callbacks).create!(name: "Crowe the One-Eyed")
@pirate.send(association_name_with_callbacks).each(&:mark_for_destruction)
child_id = @pirate.send(association_name_with_callbacks).first.id
@ -1108,8 +1108,8 @@ class TestAutosaveAssociationOnAHasOneAssociation < ActiveRecord::TestCase
def setup
super
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@ship = @pirate.create_ship(:name => "Nights Dirty Lightning")
@pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?")
@ship = @pirate.create_ship(name: "Nights Dirty Lightning")
end
def test_should_still_work_without_an_associated_model
@ -1158,7 +1158,7 @@ def test_should_merge_errors_on_the_associated_models_onto_the_parent_even_if_it
def test_should_not_ignore_different_error_messages_on_the_same_attribute
old_validators = Ship._validators.deep_dup
old_callbacks = Ship._validate_callbacks.deep_dup
Ship.validates_format_of :name, :with => /\w/
Ship.validates_format_of :name, with: /\w/
@pirate.ship.name = ""
@pirate.catchphrase = nil
assert @pirate.invalid?
@ -1171,7 +1171,7 @@ def test_should_not_ignore_different_error_messages_on_the_same_attribute
def test_should_still_allow_to_bypass_validations_on_the_associated_model
@pirate.catchphrase = ""
@pirate.ship.name = ""
@pirate.save(:validate => false)
@pirate.save(validate: false)
# Oracle saves empty string as NULL
if current_adapter?(:OracleAdapter)
assert_equal [nil, nil], [@pirate.reload.catchphrase, @pirate.ship.name]
@ -1181,12 +1181,12 @@ def test_should_still_allow_to_bypass_validations_on_the_associated_model
end
def test_should_allow_to_bypass_validations_on_associated_models_at_any_depth
2.times { |i| @pirate.ship.parts.create!(:name => "part #{i}") }
2.times { |i| @pirate.ship.parts.create!(name: "part #{i}") }
@pirate.catchphrase = ""
@pirate.ship.name = ""
@pirate.ship.parts.each { |part| part.name = "" }
@pirate.save(:validate => false)
@pirate.save(validate: false)
values = [@pirate.reload.catchphrase, @pirate.ship.name, *@pirate.ship.parts.map(&:name)]
# Oracle saves empty string as NULL
@ -1205,8 +1205,8 @@ def test_should_still_raise_an_ActiveRecordRecord_Invalid_exception_if_we_want_t
end
def test_should_not_save_and_return_false_if_a_callback_cancelled_saving
pirate = Pirate.new(:catchphrase => "Arr")
ship = pirate.build_ship(:name => "The Vile Insanity")
pirate = Pirate.new(catchphrase: "Arr")
ship = pirate.build_ship(name: "The Vile Insanity")
ship.cancel_save_from_callback = true
assert_no_difference "Pirate.count" do
@ -1272,8 +1272,8 @@ class TestAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase
def setup
super
@ship = Ship.create(:name => "Nights Dirty Lightning")
@pirate = @ship.create_pirate(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@ship = Ship.create(name: "Nights Dirty Lightning")
@pirate = @ship.create_pirate(catchphrase: "Don' botharrr talkin' like one, savvy?")
end
def test_should_still_work_without_an_associated_model
@ -1312,7 +1312,7 @@ def test_should_merge_errors_on_the_associated_model_onto_the_parent_even_if_it_
def test_should_still_allow_to_bypass_validations_on_the_associated_model
@ship.pirate.catchphrase = ""
@ship.name = ""
@ship.save(:validate => false)
@ship.save(validate: false)
# Oracle saves empty string as NULL
if current_adapter?(:OracleAdapter)
assert_equal [nil, nil], [@ship.reload.name, @ship.pirate.catchphrase]
@ -1329,8 +1329,8 @@ def test_should_still_raise_an_ActiveRecordRecord_Invalid_exception_if_we_want_t
end
def test_should_not_save_and_return_false_if_a_callback_cancelled_saving
ship = Ship.new(:name => "The Vile Insanity")
pirate = ship.build_pirate(:catchphrase => "Arr")
ship = Ship.new(name: "The Vile Insanity")
pirate = ship.build_pirate(catchphrase: "Arr")
pirate.cancel_save_from_callback = true
assert_no_difference "Ship.count" do
@ -1399,7 +1399,7 @@ def test_should_automatically_validate_the_associated_models
end
def test_should_not_use_default_invalid_error_on_associated_models
@pirate.send(@association_name).build(:name => "")
@pirate.send(@association_name).build(name: "")
assert !@pirate.valid?
assert_equal ["can't be blank"], @pirate.errors["#{@association_name}.name"]
@ -1434,7 +1434,7 @@ def test_should_allow_to_bypass_validations_on_the_associated_models_on_update
@pirate.catchphrase = ""
@pirate.send(@association_name).each { |child| child.name = "" }
assert @pirate.save(:validate => false)
assert @pirate.save(validate: false)
# Oracle saves empty string as NULL
if current_adapter?(:OracleAdapter)
assert_equal [nil, nil, nil], [
@ -1461,7 +1461,7 @@ def test_should_validation_the_associated_models_on_create
def test_should_allow_to_bypass_validations_on_the_associated_models_on_create
assert_difference("#{ @association_name == :birds ? 'Bird' : 'Parrot' }.count", 2) do
2.times { @pirate.send(@association_name).build }
@pirate.save(:validate => false)
@pirate.save(validate: false)
end
end
@ -1474,8 +1474,8 @@ def test_should_not_save_and_return_false_if_a_callback_cancelled_saving_in_eith
assert_equal "Don' botharrr talkin' like one, savvy?", @pirate.reload.catchphrase
assert_equal "Posideons Killer", @child_1.reload.name
new_pirate = Pirate.new(:catchphrase => "Arr")
new_child = new_pirate.send(@association_name).build(:name => "Grace OMalley")
new_pirate = Pirate.new(catchphrase: "Arr")
new_child = new_pirate.send(@association_name).build(name: "Grace OMalley")
new_child.cancel_save_from_callback = true
assert_no_difference "Pirate.count" do
@ -1533,9 +1533,9 @@ def setup
@association_name = :birds
@associated_model_name = :bird
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@child_1 = @pirate.birds.create(:name => "Posideons Killer")
@child_2 = @pirate.birds.create(:name => "Killer bandita Dionne")
@pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?")
@child_1 = @pirate.birds.create(name: "Posideons Killer")
@child_2 = @pirate.birds.create(name: "Killer bandita Dionne")
end
include AutosaveAssociationOnACollectionAssociationTests
@ -1580,8 +1580,8 @@ class TestAutosaveAssociationValidationsOnAHasManyAssociation < ActiveRecord::Te
def setup
super
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@pirate.birds.create(:name => "cookoo")
@pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?")
@pirate.birds.create(name: "cookoo")
end
test "should automatically validate associations" do
@ -1597,8 +1597,8 @@ class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::Tes
def setup
super
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@pirate.create_ship(:name => "titanic")
@pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?")
@pirate.create_ship(name: "titanic")
super
end
@ -1620,18 +1620,18 @@ class TestAutosaveAssociationValidationsOnABelongsToAssociation < ActiveRecord::
def setup
super
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?")
end
test "should automatically validate associations with :validate => true" do
assert @pirate.valid?
@pirate.parrot = Parrot.new(:name => "")
@pirate.parrot = Parrot.new(name: "")
assert !@pirate.valid?
end
test "should not automatically validate associations without :validate => true" do
assert @pirate.valid?
@pirate.non_validated_parrot = Parrot.new(:name => "")
@pirate.non_validated_parrot = Parrot.new(name: "")
assert @pirate.valid?
end
end
@ -1641,19 +1641,19 @@ class TestAutosaveAssociationValidationsOnAHABTMAssociation < ActiveRecord::Test
def setup
super
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?")
end
test "should automatically validate associations with :validate => true" do
assert @pirate.valid?
@pirate.parrots = [ Parrot.new(:name => "popuga") ]
@pirate.parrots = [ Parrot.new(name: "popuga") ]
@pirate.parrots.each { |parrot| parrot.name = "" }
assert !@pirate.valid?
end
test "should not automatically validate associations without :validate => true" do
assert @pirate.valid?
@pirate.non_validated_parrots = [ Parrot.new(:name => "popuga") ]
@pirate.non_validated_parrots = [ Parrot.new(name: "popuga") ]
@pirate.non_validated_parrots.each { |parrot| parrot.name = "" }
assert @pirate.valid?
end
@ -1695,6 +1695,6 @@ def setup
class TestAutosaveAssociationWithTouch < ActiveRecord::TestCase
def test_autosave_with_touch_should_not_raise_system_stack_error
invoice = Invoice.create
assert_nothing_raised { invoice.line_items.create(:amount => 10) }
assert_nothing_raised { invoice.line_items.create(amount: 10) }
end
end

@ -295,7 +295,7 @@ def test_initialize_with_invalid_attribute
end
def test_create_after_initialize_without_block
cb = CustomBulb.create(:name => "Dude")
cb = CustomBulb.create(name: "Dude")
assert_equal("Dude", cb.name)
assert_equal(true, cb.frickinawesome)
end
@ -315,13 +315,13 @@ def test_create_after_initialize_with_array_param
end
def test_load
topics = Topic.all.merge!(:order => "id").to_a
topics = Topic.all.merge!(order: "id").to_a
assert_equal(5, topics.size)
assert_equal(topics(:first).title, topics.first.title)
end
def test_load_with_condition
topics = Topic.all.merge!(:where => "author_name = 'Mary'").to_a
topics = Topic.all.merge!(where: "author_name = 'Mary'").to_a
assert_equal(1, topics.size)
assert_equal(topics(:second).title, topics.first.title)
@ -443,7 +443,7 @@ def test_singular_table_name_guesses_for_individual_table
if current_adapter?(:Mysql2Adapter)
def test_update_all_with_order_and_limit
assert_equal 1, Topic.limit(1).order("id DESC").update_all(:content => "bulk updated!")
assert_equal 1, Topic.limit(1).order("id DESC").update_all(content: "bulk updated!")
end
end
@ -536,7 +536,7 @@ def test_equality_of_new_records
end
def test_equality_of_destroyed_records
topic_1 = Topic.new(:title => "test_1")
topic_1 = Topic.new(title: "test_1")
topic_1.save
topic_2 = Topic.find(topic_1.id)
topic_1.destroy
@ -545,8 +545,8 @@ def test_equality_of_destroyed_records
end
def test_equality_with_blank_ids
one = Subscriber.new(:id => "")
two = Subscriber.new(:id => "")
one = Subscriber.new(id: "")
two = Subscriber.new(id: "")
assert_equal one, two
end
@ -604,7 +604,7 @@ def test_failed_comparison_of_unlike_class_records
def test_create_without_prepared_statement
topic = Topic.connection.unprepared_statement do
Topic.create(:title => "foo")
Topic.create(title: "foo")
end
assert_equal topic, Topic.find(topic.id)
@ -621,7 +621,7 @@ def test_destroy_without_prepared_statement
def test_comparison_with_different_objects
topic = Topic.create
category = Category.create(:name => "comparison")
category = Category.create(name: "comparison")
assert_nil topic <=> category
end
@ -635,7 +635,7 @@ def test_comparison_with_different_objects_in_array
def test_readonly_attributes
assert_equal Set.new([ "title" , "comments_count" ]), ReadonlyTitlePost.readonly_attributes
post = ReadonlyTitlePost.create(:title => "cannot change this", :body => "changeable")
post = ReadonlyTitlePost.create(title: "cannot change this", body: "changeable")
post.reload
assert_equal "cannot change this", post.title
@ -647,7 +647,7 @@ def test_readonly_attributes
def test_unicode_column_name
Weird.reset_column_information
weird = Weird.create(: => "たこ焼き仮面")
weird = Weird.create(: "たこ焼き仮面")
assert_equal "たこ焼き仮面", weird.
end
@ -790,7 +790,7 @@ def test_dup
def test_dup_with_aggregate_of_same_name_as_attribute
developer_with_aggregate = Class.new(ActiveRecord::Base) do
self.table_name = "developers"
composed_of :salary, :class_name => "BasicsTest::DeveloperSalary", :mapping => [%w(salary amount)]
composed_of :salary, class_name: "BasicsTest::DeveloperSalary", mapping: [%w(salary amount)]
end
dev = developer_with_aggregate.find(1)
@ -837,7 +837,7 @@ def test_clone_of_new_object_with_defaults
end
def test_clone_of_new_object_marks_attributes_as_dirty
developer = Developer.new :name => "Bjorn", :salary => 100000
developer = Developer.new name: "Bjorn", salary: 100000
assert developer.name_changed?
assert developer.salary_changed?
@ -847,7 +847,7 @@ def test_clone_of_new_object_marks_attributes_as_dirty
end
def test_clone_of_new_object_marks_as_dirty_only_changed_attributes
developer = Developer.new :name => "Bjorn"
developer = Developer.new name: "Bjorn"
assert developer.name_changed? # obviously
assert !developer.salary_changed? # attribute has non-nil default value, so treated as not changed
@ -857,7 +857,7 @@ def test_clone_of_new_object_marks_as_dirty_only_changed_attributes
end
def test_dup_of_saved_object_marks_attributes_as_dirty
developer = Developer.create! :name => "Bjorn", :salary => 100000
developer = Developer.create! name: "Bjorn", salary: 100000
assert !developer.name_changed?
assert !developer.salary_changed?
@ -867,7 +867,7 @@ def test_dup_of_saved_object_marks_attributes_as_dirty
end
def test_dup_of_saved_object_marks_as_dirty_only_changed_attributes
developer = Developer.create! :name => "Bjorn"
developer = Developer.create! name: "Bjorn"
assert !developer.name_changed? # both attributes of saved object should be treated as not changed
assert !developer.salary_changed?
@ -911,10 +911,10 @@ class NumericData < ActiveRecord::Base
def test_big_decimal_conditions
m = NumericData.new(
:bank_balance => 1586.43,
:big_bank_balance => BigDecimal("1000234000567.95"),
:world_population => 6000000000,
:my_house_population => 3
bank_balance: 1586.43,
big_bank_balance: BigDecimal("1000234000567.95"),
world_population: 6000000000,
my_house_population: 3
)
assert m.save
assert_equal 0, NumericData.where("bank_balance > ?", 2000.0).count
@ -922,10 +922,10 @@ def test_big_decimal_conditions
def test_numeric_fields
m = NumericData.new(
:bank_balance => 1586.43,
:big_bank_balance => BigDecimal("1000234000567.95"),
:world_population => 6000000000,
:my_house_population => 3
bank_balance: 1586.43,
big_bank_balance: BigDecimal("1000234000567.95"),
world_population: 6000000000,
my_house_population: 3
)
assert m.save
@ -950,10 +950,10 @@ def test_numeric_fields
def test_numeric_fields_with_scale
m = NumericData.new(
:bank_balance => 1586.43122334,
:big_bank_balance => BigDecimal("234000567.952344"),
:world_population => 6000000000,
:my_house_population => 3
bank_balance: 1586.43122334,
big_bank_balance: BigDecimal("234000567.952344"),
world_population: 6000000000,
my_house_population: 3
)
assert m.save
@ -999,10 +999,10 @@ def test_column_name_properly_quoted
end
def test_quoting_arrays
replies = Reply.all.merge!(:where => [ "id IN (?)", topics(:first).replies.collect(&:id) ]).to_a
replies = Reply.all.merge!(where: [ "id IN (?)", topics(:first).replies.collect(&:id) ]).to_a
assert_equal topics(:first).replies.size, replies.size
replies = Reply.all.merge!(:where => [ "id IN (?)", [] ]).to_a
replies = Reply.all.merge!(where: [ "id IN (?)", [] ]).to_a
assert_equal 0, replies.size
end
@ -1149,17 +1149,17 @@ def test_count_with_join
def test_no_limit_offset
assert_nothing_raised do
Developer.all.merge!(:offset => 2).to_a
Developer.all.merge!(offset: 2).to_a
end
end
def test_find_last
last = Developer.last
assert_equal last, Developer.all.merge!(:order => "id desc").first
assert_equal last, Developer.all.merge!(order: "id desc").first
end
def test_last
assert_equal Developer.all.merge!(:order => "id desc").first, Developer.last
assert_equal Developer.all.merge!(order: "id desc").first, Developer.last
end
def test_all
@ -1169,37 +1169,37 @@ def test_all
end
def test_all_with_conditions
assert_equal Developer.all.merge!(:order => "id desc").to_a, Developer.order("id desc").to_a
assert_equal Developer.all.merge!(order: "id desc").to_a, Developer.order("id desc").to_a
end
def test_find_ordered_last
last = Developer.all.merge!(:order => "developers.salary ASC").last
assert_equal last, Developer.all.merge!(:order => "developers.salary ASC").to_a.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.all.merge!(:order => "developers.salary DESC").last
assert_equal last, Developer.all.merge!(:order => "developers.salary DESC").to_a.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.all.merge!(:order => "developers.name, developers.salary DESC").last
assert_equal last, Developer.all.merge!(:order => "developers.name, developers.salary DESC").to_a.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.all.merge!(:order => "developers.name, developers.salary").to_a
assert_equal combined, Developer.all.merge!(:order => ["developers.name", "developers.salary"]).to_a
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.all.merge!(:group => "developers.name, developers.salary, developers.id, developers.created_at, developers.updated_at, developers.created_on, developers.updated_on").to_a
assert_equal combined, Developer.all.merge!(:group => ["developers.name", "developers.salary", "developers.id", "developers.created_at", "developers.updated_at", "developers.created_on", "developers.updated_on"]).to_a
combined = Developer.all.merge!(group: "developers.name, developers.salary, developers.id, developers.created_at, developers.updated_at, developers.created_on, developers.updated_on").to_a
assert_equal combined, Developer.all.merge!(group: ["developers.name", "developers.salary", "developers.id", "developers.created_at", "developers.updated_at", "developers.created_on", "developers.updated_on"]).to_a
end
def test_find_symbol_ordered_last
last = Developer.all.merge!(:order => :salary).last
assert_equal last, Developer.all.merge!(:order => :salary).to_a.last
last = Developer.all.merge!(order: :salary).last
assert_equal last, Developer.all.merge!(order: :salary).to_a.last
end
def test_abstract_class_table_name
@ -1210,7 +1210,7 @@ def test_find_on_abstract_base_class_doesnt_use_type_condition
old_class = LooseDescendant
Object.send :remove_const, :LooseDescendant
descendant = old_class.create! :first_name => "bob"
descendant = old_class.create! first_name: "bob"
assert_not_nil LoosePerson.find(descendant.id), "Should have found instance of LooseDescendant when finding abstract LoosePerson: #{descendant.inspect}"
ensure
unless Object.const_defined?(:LooseDescendant)
@ -1230,9 +1230,9 @@ def test_benchmark_with_log_level
log = StringIO.new
ActiveRecord::Base.logger = ActiveSupport::Logger.new(log)
ActiveRecord::Base.logger.level = Logger::WARN
ActiveRecord::Base.benchmark("Debug Topic Count", :level => :debug) { Topic.count }
ActiveRecord::Base.benchmark("Warn Topic Count", :level => :warn) { Topic.count }
ActiveRecord::Base.benchmark("Error Topic Count", :level => :error) { Topic.count }
ActiveRecord::Base.benchmark("Debug Topic Count", level: :debug) { Topic.count }
ActiveRecord::Base.benchmark("Warn Topic Count", level: :warn) { Topic.count }
ActiveRecord::Base.benchmark("Error Topic Count", level: :error) { Topic.count }
assert_no_match(/Debug Topic Count/, log.string)
assert_match(/Warn Topic Count/, log.string)
assert_match(/Error Topic Count/, log.string)
@ -1245,7 +1245,7 @@ def test_benchmark_with_use_silence
log = StringIO.new
ActiveRecord::Base.logger = ActiveSupport::Logger.new(log)
ActiveRecord::Base.logger.level = Logger::DEBUG
ActiveRecord::Base.benchmark("Logging", :level => :debug, :silence => false) { ActiveRecord::Base.logger.debug "Quiet" }
ActiveRecord::Base.benchmark("Logging", level: :debug, silence: false) { ActiveRecord::Base.logger.debug "Quiet" }
assert_match(/Quiet/, log.string)
ensure
ActiveRecord::Base.logger = original_logger
@ -1367,7 +1367,7 @@ def test_attribute_names_on_abstract_class
end
def test_touch_should_raise_error_on_a_new_object
company = Company.new(:rating => 1, :name => "37signals", :firm_name => "37signals")
company = Company.new(rating: 1, name: "37signals", firm_name: "37signals")
assert_raises(ActiveRecord::ActiveRecordError) do
company.touch :updated_at
end
@ -1411,7 +1411,7 @@ def test_typecasting_aliases
end
def test_slice
company = Company.new(:rating => 1, :name => "37signals", :firm_name => "37signals")
company = Company.new(rating: 1, name: "37signals", firm_name: "37signals")
hash = company.slice(:name, :rating, "arbitrary_method")
assert_equal hash[:name], company.name
assert_equal hash["name"], company.name

@ -13,7 +13,7 @@ def setup
def test_each_should_execute_one_query_per_batch
assert_queries(@total + 1) do
Post.find_each(:batch_size => 1) do |post|
Post.find_each(batch_size: 1) do |post|
assert_kind_of Post, post
end
end
@ -21,14 +21,14 @@ def test_each_should_execute_one_query_per_batch
def test_each_should_not_return_query_chain_and_execute_only_one_query
assert_queries(1) do
result = Post.find_each(:batch_size => 100000){ }
result = Post.find_each(batch_size: 100000){ }
assert_nil result
end
end
def test_each_should_return_an_enumerator_if_no_block_is_present
assert_queries(1) do
Post.find_each(:batch_size => 100000).with_index do |post, index|
Post.find_each(batch_size: 100000).with_index do |post, index|
assert_kind_of Post, post
assert_kind_of Integer, index
end
@ -45,7 +45,7 @@ def test_each_should_return_a_sized_enumerator
def test_each_enumerator_should_execute_one_query_per_batch
assert_queries(@total + 1) do
Post.find_each(:batch_size => 1).with_index do |post, index|
Post.find_each(batch_size: 1).with_index do |post, index|
assert_kind_of Post, post
assert_kind_of Integer, index
end
@ -62,7 +62,7 @@ def test_each_should_raise_if_select_is_set_without_id
def test_each_should_execute_if_id_is_in_select
assert_queries(6) do
Post.select("id, title, type").find_each(:batch_size => 2) do |post|
Post.select("id, title, type").find_each(batch_size: 2) do |post|
assert_kind_of Post, post
end
end
@ -108,7 +108,7 @@ def test_logger_not_required
def test_find_in_batches_should_return_batches
assert_queries(@total + 1) do
Post.find_in_batches(:batch_size => 1) do |batch|
Post.find_in_batches(batch_size: 1) do |batch|
assert_kind_of Array, batch
assert_kind_of Post, batch.first
end
@ -135,18 +135,18 @@ def test_find_in_batches_should_end_at_the_finish_option
def test_find_in_batches_shouldnt_execute_query_unless_needed
assert_queries(2) do
Post.find_in_batches(:batch_size => @total) {|batch| assert_kind_of Array, batch }
Post.find_in_batches(batch_size: @total) {|batch| assert_kind_of Array, batch }
end
assert_queries(1) do
Post.find_in_batches(:batch_size => @total + 1) {|batch| assert_kind_of Array, batch }
Post.find_in_batches(batch_size: @total + 1) {|batch| assert_kind_of Array, batch }
end
end
def test_find_in_batches_should_quote_batch_order
c = Post.connection
assert_sql(/ORDER BY #{c.quote_table_name('posts')}.#{c.quote_column_name('id')}/) do
Post.find_in_batches(:batch_size => 1) do |batch|
Post.find_in_batches(batch_size: 1) do |batch|
assert_kind_of Array, batch
assert_kind_of Post, batch.first
end
@ -158,7 +158,7 @@ def test_find_in_batches_should_not_use_records_after_yielding_them_in_case_orig
def not_a_post.id; end
not_a_post.stub(:id, ->{ raise StandardError.new("not_a_post had #id called on it") }) do
assert_nothing_raised do
Post.find_in_batches(:batch_size => 1) do |batch|
Post.find_in_batches(batch_size: 1) do |batch|
assert_kind_of Array, batch
assert_kind_of Post, batch.first
@ -255,7 +255,7 @@ def test_find_in_batches_should_use_any_column_as_primary_key_when_start_is_not_
def test_find_in_batches_should_return_an_enumerator
enum = nil
assert_no_queries do
enum = Post.find_in_batches(:batch_size => 1)
enum = Post.find_in_batches(batch_size: 1)
end
assert_queries(4) do
enum.first(4) do |batch|
@ -517,11 +517,11 @@ def test_in_batches_relations_update_all_should_not_affect_matching_records_in_o
if Enumerator.method_defined? :size
def test_find_in_batches_should_return_a_sized_enumerator
assert_equal 11, Post.find_in_batches(:batch_size => 1).size
assert_equal 6, Post.find_in_batches(:batch_size => 2).size
assert_equal 11, Post.find_in_batches(batch_size: 1).size
assert_equal 6, Post.find_in_batches(batch_size: 2).size
assert_equal 4, Post.find_in_batches(batch_size: 2, start: 4).size
assert_equal 4, Post.find_in_batches(:batch_size => 3).size
assert_equal 1, Post.find_in_batches(:batch_size => 10_000).size
assert_equal 4, Post.find_in_batches(batch_size: 3).size
assert_equal 1, Post.find_in_batches(batch_size: 10_000).size
end
end

@ -13,7 +13,7 @@ def test_mixed_encoding
str = "\x80"
str.force_encoding("ASCII-8BIT")
binary = Binary.new :name => "いただきます!", :data => str
binary = Binary.new name: "いただきます!", data: str
binary.save!
binary.reload
assert_equal str, binary.data
@ -31,7 +31,7 @@ def test_load_save
data.force_encoding("ASCII-8BIT")
data.freeze
bin = Binary.new(:data => data)
bin = Binary.new(data: data)
assert_equal data, bin.data, "Newly assigned data differs from original"
bin.save!

@ -60,10 +60,10 @@ def test_logs_bind_vars_after_type_cast
binds = [Relation::QueryAttribute.new("id", "10", Type::Integer.new)]
type_casted_binds = binds.map { |attr| type_cast(attr.value_for_database) }
payload = {
:name => "SQL",
:sql => "select * from topics where id = ?",
:binds => binds,
:type_casted_binds => type_casted_binds
name: "SQL",
sql: "select * from topics where id = ?",
binds: binds,
type_casted_binds: type_casted_binds
}
event = ActiveSupport::Notifications::Event.new(
"foo",

@ -57,7 +57,7 @@ def test_should_return_decimal_average_of_integer_field
def test_should_return_integer_average_if_db_returns_such
ShipPart.delete_all
ShipPart.create!(:id => 3, :name => "foo")
ShipPart.create!(id: 3, name: "foo")
value = ShipPart.average(:id)
assert_equal 3, value
end
@ -258,7 +258,7 @@ def test_should_return_zero_if_sum_conditions_return_nothing
end
def test_sum_should_return_valid_values_for_decimals
NumericData.create(:bank_balance => 19.83)
NumericData.create(bank_balance: 19.83)
assert_equal 19.83, NumericData.sum(:bank_balance)
end
@ -318,7 +318,7 @@ def test_should_group_by_association_with_non_numeric_foreign_key
end
def test_should_calculate_grouped_association_with_foreign_key_option
Account.belongs_to :another_firm, :class_name => "Firm", :foreign_key => "firm_id"
Account.belongs_to :another_firm, class_name: "Firm", foreign_key: "firm_id"
c = Account.group(:another_firm).count(:all)
assert_equal 1, c[companies(:first_firm)]
assert_equal 2, c[companies(:rails_core)]
@ -381,7 +381,7 @@ def test_should_not_perform_joined_include_by_default
end
def test_should_perform_joined_include_when_referencing_included_tables
joined_count = Account.includes(:firm).where(:companies => {:name => "37signals"}).count
joined_count = Account.includes(:firm).where(companies: {name: "37signals"}).count
assert_equal 1, joined_count
end
@ -504,8 +504,8 @@ def test_count_with_from_option
assert_equal Company.count(:all), Company.from("companies").count(:all)
assert_equal Account.where("credit_limit = 50").count(:all),
Account.from("accounts").where("credit_limit = 50").count(:all)
assert_equal Company.where(:type => "Firm").count(:type),
Company.where(:type => "Firm").from("companies").count(:type)
assert_equal Company.where(type: "Firm").count(:type),
Company.where(type: "Firm").from("companies").count(:type)
end
def test_sum_with_from_option
@ -533,19 +533,19 @@ def test_maximum_with_from_option
end
def test_maximum_with_not_auto_table_name_prefix_if_column_included
Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)])
assert_equal 7, Company.includes(:contracts).maximum(:developer_id)
end
def test_minimum_with_not_auto_table_name_prefix_if_column_included
Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)])
assert_equal 7, Company.includes(:contracts).minimum(:developer_id)
end
def test_sum_with_not_auto_table_name_prefix_if_column_included
Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)])
assert_equal 7, Company.includes(:contracts).sum(:developer_id)
end
@ -582,7 +582,7 @@ def test_pluck_without_column_names
def test_pluck_type_cast
topic = topics(:first)
relation = Topic.where(:id => topic.id)
relation = Topic.where(id: topic.id)
assert_equal [ topic.approved ], relation.pluck(:approved)
assert_equal [ topic.last_read ], relation.pluck(:last_read)
assert_equal [ topic.written_on ], relation.pluck(:written_on)
@ -603,8 +603,8 @@ def test_pluck_on_aliased_attribute
end
def test_pluck_with_serialization
t = Topic.create!(:content => { :foo => :bar })
assert_equal [{:foo => :bar}], Topic.where(:id => t.id).pluck(:content)
t = Topic.create!(content: { foo: :bar })
assert_equal [{foo: :bar}], Topic.where(id: t.id).pluck(:content)
end
def test_pluck_with_qualified_column_name
@ -612,17 +612,17 @@ def test_pluck_with_qualified_column_name
end
def test_pluck_auto_table_name_prefix
c = Company.create!(:name => "test", :contracts => [Contract.new])
c = Company.create!(name: "test", contracts: [Contract.new])
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)])
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)])
Company.create!(name: "test", contracts: [Contract.new(developer_id: 7)])
assert_equal [7], Company.joins(:contracts).pluck(:developer_id)
end
@ -647,7 +647,7 @@ def test_pluck_with_includes_limit_and_empty_result
end
def test_pluck_not_auto_table_name_prefix_if_column_included
Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
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
@ -672,7 +672,7 @@ def test_pluck_with_multiple_columns_and_selection_clause
end
def test_pluck_with_multiple_columns_and_includes
Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
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
@ -681,7 +681,7 @@ def test_pluck_with_multiple_columns_and_includes
end
def test_pluck_with_reserved_words
Possession.create!(:where => "Over There")
Possession.create!(where: "Over There")
assert_equal ["Over There"], Possession.pluck(:where)
end

@ -67,7 +67,7 @@ class ChildDeveloper < ParentDeveloper
class ImmutableDeveloper < ActiveRecord::Base
self.table_name = "developers"
validates_inclusion_of :salary, :in => 50000..200000
validates_inclusion_of :salary, in: 50000..200000
before_save :cancel
before_destroy :cancel
@ -96,16 +96,16 @@ class OnCallbacksDeveloper < ActiveRecord::Base
self.table_name = "developers"
before_validation { history << :before_validation }
before_validation(:on => :create){ history << :before_validation_on_create }
before_validation(:on => :update){ history << :before_validation_on_update }
before_validation(on: :create){ history << :before_validation_on_create }
before_validation(on: :update){ history << :before_validation_on_update }
validate do
history << :validate
end
after_validation { history << :after_validation }
after_validation(:on => :create){ history << :after_validation_on_create }
after_validation(:on => :update){ history << :after_validation_on_update }
after_validation(on: :create){ history << :after_validation_on_create }
after_validation(on: :update){ history << :after_validation_on_update }
def history
@history ||= []
@ -116,14 +116,14 @@ class ContextualCallbacksDeveloper < ActiveRecord::Base
self.table_name = "developers"
before_validation { history << :before_validation }
before_validation :before_validation_on_create_and_update, :on => [ :create, :update ]
before_validation :before_validation_on_create_and_update, on: [ :create, :update ]
validate do
history << :validate
end
after_validation { history << :after_validation }
after_validation :after_validation_on_create_and_update, :on => [ :create, :update ]
after_validation :after_validation_on_create_and_update, on: [ :create, :update ]
def before_validation_on_create_and_update
history << "before_validation_on_#{self.validation_context}".to_sym

@ -6,7 +6,7 @@ class ColumnDefinitionTest < ActiveRecord::TestCase
def setup
@adapter = AbstractAdapter.new(nil)
def @adapter.native_database_types
{:string => "varchar"}
{string: "varchar"}
end
@viz = @adapter.schema_creation
end

@ -4,7 +4,7 @@ module ActiveRecord
module ConnectionAdapters
class ConnectionSpecificationTest < ActiveRecord::TestCase
def test_dup_deep_copy_config
spec = ConnectionSpecification.new("primary", { :a => :b }, "bar")
spec = ConnectionSpecification.new("primary", { a: :b }, "bar")
assert_not_equal(spec.config.object_id, spec.dup.config.object_id)
end
end

@ -25,8 +25,8 @@ def test_inspect_new_instance
end
def test_inspect_limited_select_instance
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
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

@ -19,12 +19,12 @@ class CounterCacheTest < ActiveRecord::TestCase
fixtures :topics, :categories, :categorizations, :cars, :dogs, :dog_lovers, :people, :friendships, :subscribers, :subscriptions, :books
class ::SpecialTopic < ::Topic
has_many :special_replies, :foreign_key => "parent_id"
has_many :lightweight_special_replies, -> { select("topics.id, topics.title") }, :foreign_key => "parent_id", :class_name => "SpecialReply"
has_many :special_replies, foreign_key: "parent_id"
has_many :lightweight_special_replies, -> { select("topics.id, topics.title") }, foreign_key: "parent_id", class_name: "SpecialReply"
end
class ::SpecialReply < ::Reply
belongs_to :special_topic, :foreign_key => "parent_id", :counter_cache => "replies_count"
belongs_to :special_topic, foreign_key: "parent_id", counter_cache: "replies_count"
end
setup do
@ -79,7 +79,7 @@ class ::SpecialReply < ::Reply
end
test "reset counters with modularized and camelized classnames" do
special = SpecialTopic.create!(:title => "Special")
special = SpecialTopic.create!(title: "Special")
SpecialTopic.increment_counter(:replies_count, special.id)
assert_difference "special.reload.replies_count", -1 do
@ -116,13 +116,13 @@ class ::SpecialReply < ::Reply
assert_equal 2, category.categorizations.count
assert_nil category.categorizations_count
Category.update_counters(category.id, :categorizations_count => category.categorizations.count)
Category.update_counters(category.id, categorizations_count: category.categorizations.count)
assert_equal 2, category.reload.categorizations_count
end
test "update counter for decrement" do
assert_difference "@topic.reload.replies_count", -3 do
Topic.update_counters(@topic.id, :replies_count => -3)
Topic.update_counters(@topic.id, replies_count: -3)
end
end
@ -130,7 +130,7 @@ class ::SpecialReply < ::Reply
t1, t2 = topics(:first, :second)
assert_difference ["t1.reload.replies_count", "t2.reload.replies_count"], 2 do
Topic.update_counters([t1.id, t2.id], :replies_count => 2)
Topic.update_counters([t1.id, t2.id], replies_count: 2)
end
end
@ -174,7 +174,7 @@ class ::SpecialReply < ::Reply
end
test "reset counter works with select declared on association" do
special = SpecialTopic.create!(:title => "Special")
special = SpecialTopic.create!(title: "Special")
SpecialTopic.increment_counter(:replies_count, special.id)
assert_difference "special.reload.replies_count", -1 do

@ -9,7 +9,7 @@ def test_custom_lock
if current_adapter?(:Mysql2Adapter)
assert_match "SHARE MODE", Person.lock("LOCK IN SHARE MODE").to_sql
assert_sql(/LOCK IN SHARE MODE/) do
Person.all.merge!(:lock => "LOCK IN SHARE MODE").find(1)
Person.all.merge!(lock: "LOCK IN SHARE MODE").find(1)
end
end
end

@ -178,10 +178,10 @@ def with_text_blob_not_null_table
klass = Class.new(ActiveRecord::Base)
klass.table_name = "test_mysql_text_not_null_defaults"
klass.connection.create_table klass.table_name do |t|
t.column :non_null_text, :text, :null => false
t.column :non_null_blob, :blob, :null => false
t.column :null_text, :text, :null => true
t.column :null_blob, :blob, :null => true
t.column :non_null_text, :text, null: false
t.column :non_null_blob, :blob, null: false
t.column :null_text, :text, null: true
t.column :null_blob, :blob, null: true
end
yield klass
@ -195,8 +195,8 @@ def test_mysql_integer_not_null_defaults
klass = Class.new(ActiveRecord::Base)
klass.table_name = "test_integer_not_null_default_zero"
klass.connection.create_table klass.table_name do |t|
t.column :zero, :integer, :null => false, :default => 0
t.column :omit, :integer, :null => false
t.column :zero, :integer, null: false, default: 0
t.column :omit, :integer, null: false
end
assert_equal "0", klass.columns_hash["zero"].default
@ -207,7 +207,7 @@ def test_mysql_integer_not_null_defaults
assert_raise(ActiveRecord::StatementInvalid) { klass.create! }
assert_nothing_raised do
instance = klass.create!(:omit => 1)
instance = klass.create!(omit: 1)
assert_equal 0, instance.zero
assert_equal 1, instance.omit
end

@ -14,7 +14,7 @@ class DirtyTest < ActiveRecord::TestCase
# Dummy to force column loads so query counts are clean.
def setup
Person.create :first_name => "foo"
Person.create first_name: "foo"
end
def test_attribute_changes
@ -149,7 +149,7 @@ def test_aliased_attribute_changes
end
def test_restore_attribute!
pirate = Pirate.create!(:catchphrase => "Yar!")
pirate = Pirate.create!(catchphrase: "Yar!")
pirate.catchphrase = "Ahoy!"
pirate.restore_catchphrase!
@ -229,7 +229,7 @@ def test_integer_zero_to_integer_zero_not_marked_as_changed
end
def test_float_zero_to_string_zero_not_marked_as_changed
data = NumericData.new :temperature => 0.0
data = NumericData.new temperature: 0.0
data.save!
assert_not data.changed?
@ -290,7 +290,7 @@ def test_object_should_be_changed_if_any_attribute_is_changed
end
def test_attribute_will_change!
pirate = Pirate.create!(:catchphrase => "arr")
pirate = Pirate.create!(catchphrase: "arr")
assert !pirate.catchphrase_changed?
assert pirate.catchphrase_will_change!
@ -303,8 +303,8 @@ def test_attribute_will_change!
end
def test_association_assignment_changes_foreign_key
pirate = Pirate.create!(:catchphrase => "jarl")
pirate.parrot = Parrot.create!(:name => "Lorre")
pirate = Pirate.create!(catchphrase: "jarl")
pirate.parrot = Parrot.create!(name: "Lorre")
assert pirate.changed?
assert_equal %w(parrot_id), pirate.changed
end
@ -315,7 +315,7 @@ def test_attribute_should_be_compared_with_type_cast
assert !topic.approved_changed?
# Coming from web form.
params = {:topic => {:approved => 1}}
params = {topic: {approved: 1}}
# In the controller.
topic.attributes = params[:topic]
assert topic.approved?
@ -323,12 +323,12 @@ def test_attribute_should_be_compared_with_type_cast
end
def test_partial_update
pirate = Pirate.new(:catchphrase => "foo")
pirate = Pirate.new(catchphrase: "foo")
old_updated_on = 1.hour.ago.beginning_of_day
with_partial_writes Pirate, false do
assert_queries(2) { 2.times { pirate.save! } }
Pirate.where(id: pirate.id).update_all(:updated_on => old_updated_on)
Pirate.where(id: pirate.id).update_all(updated_on: old_updated_on)
end
with_partial_writes Pirate, true do
@ -341,12 +341,12 @@ def test_partial_update
end
def test_partial_update_with_optimistic_locking
person = Person.new(:first_name => "foo")
person = Person.new(first_name: "foo")
old_lock_version = 1
with_partial_writes Person, false do
assert_queries(2) { 2.times { person.save! } }
Person.where(id: person.id).update_all(:first_name => "baz")
Person.where(id: person.id).update_all(first_name: "baz")
end
with_partial_writes Person, true do
@ -371,7 +371,7 @@ def test_changed_attributes_should_be_preserved_if_save_failure
end
def test_reload_should_clear_changed_attributes
pirate = Pirate.create!(:catchphrase => "shiver me timbers")
pirate = Pirate.create!(catchphrase: "shiver me timbers")
pirate.catchphrase = "*hic*"
assert pirate.changed?
pirate.reload
@ -379,7 +379,7 @@ def test_reload_should_clear_changed_attributes
end
def test_dup_objects_should_not_copy_dirty_flag_from_creator
pirate = Pirate.create!(:catchphrase => "shiver me timbers")
pirate = Pirate.create!(catchphrase: "shiver me timbers")
pirate_dup = pirate.dup
pirate_dup.restore_catchphrase!
pirate.catchphrase = "I love Rum"
@ -389,7 +389,7 @@ def test_dup_objects_should_not_copy_dirty_flag_from_creator
def test_reverted_changes_are_not_dirty
phrase = "shiver me timbers"
pirate = Pirate.create!(:catchphrase => phrase)
pirate = Pirate.create!(catchphrase: phrase)
pirate.catchphrase = "*hic*"
assert pirate.changed?
pirate.catchphrase = phrase
@ -398,7 +398,7 @@ def test_reverted_changes_are_not_dirty
def test_reverted_changes_are_not_dirty_after_multiple_changes
phrase = "shiver me timbers"
pirate = Pirate.create!(:catchphrase => phrase)
pirate = Pirate.create!(catchphrase: phrase)
10.times do |i|
pirate.catchphrase = "*hic*" * i
assert pirate.changed?
@ -410,7 +410,7 @@ def test_reverted_changes_are_not_dirty_after_multiple_changes
def test_reverted_changes_are_not_dirty_going_from_nil_to_value_and_back
pirate = Pirate.create!(:catchphrase => "Yar!")
pirate = Pirate.create!(catchphrase: "Yar!")
pirate.parrot_id = 1
assert pirate.changed?
@ -425,7 +425,7 @@ def test_reverted_changes_are_not_dirty_going_from_nil_to_value_and_back
def test_save_should_store_serialized_attributes_even_with_partial_writes
with_partial_writes(Topic) do
topic = Topic.create!(:content => {:a => "a"})
topic = Topic.create!(content: {a: "a"})
assert_not topic.changed?
@ -446,7 +446,7 @@ def test_save_should_store_serialized_attributes_even_with_partial_writes
def test_save_always_should_update_timestamps_when_serialized_attributes_are_present
with_partial_writes(Topic) do
topic = Topic.create!(:content => {:a => "a"})
topic = Topic.create!(content: {a: "a"})
topic.save!
updated_at = topic.updated_at
@ -462,7 +462,7 @@ def test_save_always_should_update_timestamps_when_serialized_attributes_are_pre
def test_save_should_not_save_serialized_attribute_with_partial_writes_if_not_present
with_partial_writes(Topic) do
Topic.create!(:author_name => "Bill", :content => {:a => "a"})
Topic.create!(author_name: "Bill", content: {a: "a"})
topic = Topic.select("id, author_name").first
topic.update_columns author_name: "John"
topic = Topic.first
@ -582,7 +582,7 @@ def test_datetime_attribute_can_be_updated_with_fractional_seconds
written_on = Time.utc(2012, 12, 1, 12, 0, 0).in_time_zone("Paris")
topic = target.create(:written_on => written_on)
topic = target.create(written_on: written_on)
topic.written_on += 0.3
assert topic.written_on_changed?, "Fractional second update not detected"
@ -591,7 +591,7 @@ def test_datetime_attribute_can_be_updated_with_fractional_seconds
def test_datetime_attribute_doesnt_change_if_zone_is_modified_in_string
time_in_paris = Time.utc(2014, 1, 1, 12, 0, 0).in_time_zone("Paris")
pirate = Pirate.create!(:catchphrase => "rrrr", :created_on => time_in_paris)
pirate = Pirate.create!(catchphrase: "rrrr", created_on: time_in_paris)
pirate.created_on = pirate.created_on.in_time_zone("Tokyo").to_s
assert !pirate.created_on_changed?

@ -135,8 +135,8 @@ def test_dup_validity_is_independent
def test_dup_with_default_scope
prev_default_scopes = Topic.default_scopes
Topic.default_scopes = [proc { Topic.where(:approved => true) }]
topic = Topic.new(:approved => false)
Topic.default_scopes = [proc { Topic.where(approved: true) }]
topic = Topic.new(approved: false)
assert !topic.dup.approved?, "should not be overridden by default scopes"
ensure
Topic.default_scopes = prev_default_scopes

@ -15,13 +15,13 @@ def connection
end
def test_relation_explain
message = Car.where(:name => "honda").explain
message = Car.where(name: "honda").explain
assert_match(/^EXPLAIN for:/, message)
end
def test_collecting_queries_for_explain
queries = ActiveRecord::Base.collecting_queries_for_explain do
Car.where(:name => "honda").to_a
Car.where(name: "honda").to_a
end
sql, binds = queries[0]
@ -65,7 +65,7 @@ def test_exec_explain_with_binds
def test_unsupported_connection_adapter
connection.stub(:supports_explain?, false) do
assert_not_called(base.logger, :warn) do
Car.where(:name => "honda").to_a
Car.where(name: "honda").to_a
end
end
end

@ -23,13 +23,13 @@ class FinderTest < ActiveRecord::TestCase
def test_find_by_id_with_hash
assert_raises(ActiveRecord::StatementInvalid) do
Post.find_by_id(:limit => 1)
Post.find_by_id(limit: 1)
end
end
def test_find_by_title_and_id_with_hash
assert_raises(ActiveRecord::StatementInvalid) do
Post.find_by_title_and_id("foo", :limit => 1)
Post.find_by_title_and_id("foo", limit: 1)
end
end
@ -144,7 +144,7 @@ def test_exists
assert_equal true, Topic.exists?("1")
assert_equal true, Topic.exists?(title: "The First Topic")
assert_equal true, Topic.exists?(heading: "The First Topic")
assert_equal true, Topic.exists?(:author_name => "Mary", :approved => true)
assert_equal true, Topic.exists?(author_name: "Mary", approved: true)
assert_equal true, Topic.exists?(["parent_id = ?", 1])
assert_equal true, Topic.exists?(id: [1, 9999])
@ -231,17 +231,14 @@ def test_exists_with_empty_table_and_no_args_given
def test_exists_with_aggregate_having_three_mappings
existing_address = customers(:david).address
assert_equal true, Customer.exists?(:address => existing_address)
assert_equal true, Customer.exists?(address: existing_address)
end
def test_exists_with_aggregate_having_three_mappings_with_one_difference
existing_address = customers(:david).address
assert_equal false, Customer.exists?(:address =>
Address.new(existing_address.street, existing_address.city, existing_address.country + "1"))
assert_equal false, Customer.exists?(:address =>
Address.new(existing_address.street, existing_address.city + "1", existing_address.country))
assert_equal false, Customer.exists?(:address =>
Address.new(existing_address.street + "1", existing_address.city, existing_address.country))
assert_equal false, Customer.exists?(address: Address.new(existing_address.street, existing_address.city, existing_address.country + "1"))
assert_equal false, Customer.exists?(address: Address.new(existing_address.street, existing_address.city + "1", existing_address.country))
assert_equal false, Customer.exists?(address: Address.new(existing_address.street + "1", existing_address.city, existing_address.country))
end
def test_exists_does_not_instantiate_records
@ -672,7 +669,7 @@ def test_find_on_combined_explicit_and_hashed_table_names
end
def test_find_with_hash_conditions_on_joined_table
firms = Firm.joins(:account).where(:accounts => { :credit_limit => 50 })
firms = Firm.joins(:account).where(accounts: { credit_limit: 50 })
assert_equal 1, firms.size
assert_equal companies(:first_firm), firms.first
end
@ -772,42 +769,42 @@ def test_hash_condition_find_with_nil
def test_hash_condition_find_with_aggregate_having_one_mapping
balance = customers(:david).balance
assert_kind_of Money, balance
found_customer = Customer.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.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.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.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.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.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
@ -1042,7 +1039,7 @@ def test_find_by_id_with_conditions_with_or
end
def test_find_ignores_previously_inserted_record
Post.create!(:title => "test", :body => "it out")
Post.create!(title: "test", body: "it out")
assert_equal [], Post.where(id: nil)
end
@ -1115,8 +1112,8 @@ def test_find_with_nil_inside_set_passed_for_attribute
def test_with_limiting_with_custom_select
posts = Post.references(:authors).merge(
:includes => :author, :select => 'posts.*, authors.id as "author_id"',
:limit => 3, :order => "posts.id"
includes: :author, select: 'posts.*, authors.id as "author_id"',
limit: 3, order: "posts.id"
).to_a
assert_equal 3, posts.size
assert_equal [0, 1, 1], posts.map(&:author_id).sort

@ -81,7 +81,7 @@ def test_multiple_clean_fixtures
end
def test_create_symbol_fixtures
fixtures = ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT, :collections, :collections => Course) { Course.connection }
fixtures = ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT, :collections, collections: Course) { Course.connection }
assert Course.find_by_name("Collection"), "course is not in the database"
assert fixtures.detect { |f| f.name == "collections" }, "no fixtures named 'collections' in #{fixtures.map(&:name).inspect}"
@ -115,10 +115,10 @@ def test_inserts_with_pre_and_suffix
t.column :bonus_time, :time
t.column :last_read, :date
t.column :content, :string
t.column :approved, :boolean, :default => true
t.column :replies_count, :integer, :default => 0
t.column :approved, :boolean, default: true
t.column :replies_count, :integer, default: 0
t.column :parent_id, :integer
t.column :type, :string, :limit => 50
t.column :type, :string, limit: 50
end
# Store existing prefix/suffix
@ -291,11 +291,11 @@ def test_has_many_through_with_default_table_name
treasure = make_model "Treasure"
pt.table_name = "parrots_treasures"
pt.belongs_to :parrot, :anonymous_class => parrot
pt.belongs_to :treasure, :anonymous_class => treasure
pt.belongs_to :parrot, anonymous_class: parrot
pt.belongs_to :treasure, anonymous_class: treasure
parrot.has_many :parrot_treasures, :anonymous_class => pt
parrot.has_many :treasures, :through => :parrot_treasures
parrot.has_many :parrot_treasures, anonymous_class: pt
parrot.has_many :treasures, through: :parrot_treasures
parrots = File.join FIXTURES_ROOT, "parrots"
@ -309,11 +309,11 @@ def test_has_many_through_with_renamed_table
parrot = make_model "Parrot"
treasure = make_model "Treasure"
pt.belongs_to :parrot, :anonymous_class => parrot
pt.belongs_to :treasure, :anonymous_class => treasure
pt.belongs_to :parrot, anonymous_class: parrot
pt.belongs_to :treasure, anonymous_class: treasure
parrot.has_many :parrot_treasures, :anonymous_class => pt
parrot.has_many :treasures, :through => :parrot_treasures
parrot.has_many :parrot_treasures, anonymous_class: pt
parrot.has_many :treasures, through: :parrot_treasures
parrots = File.join FIXTURES_ROOT, "parrots"
@ -339,7 +339,7 @@ class FixturesResetPkSequenceTest < ActiveRecord::TestCase
fixtures :companies
def setup
@instances = [Account.new(:credit_limit => 50), Company.new(:name => "RoR Consulting"), Course.new(name: "Test")]
@instances = [Account.new(credit_limit: 50), Company.new(name: "RoR Consulting"), Course.new(name: "Test")]
ActiveRecord::FixtureSet.reset_cache # make sure tables get reinitialized
end
@ -553,7 +553,7 @@ def test_uses_set_fixture_class
end
class CheckSetTableNameFixturesTest < ActiveRecord::TestCase
set_fixture_class :funny_jokes => Joke
set_fixture_class funny_jokes: Joke
fixtures :funny_jokes
# Set to false to blow away fixtures cache and ensure our fixtures are loaded
# and thus takes into account our set_fixture_class
@ -565,7 +565,7 @@ def test_table_method
end
class FixtureNameIsNotTableNameFixturesTest < ActiveRecord::TestCase
set_fixture_class :items => Book
set_fixture_class items: Book
fixtures :items
# Set to false to blow away fixtures cache and ensure our fixtures are loaded
# and thus takes into account our set_fixture_class
@ -577,7 +577,7 @@ def test_named_accessor
end
class FixtureNameIsNotTableNameMultipleFixturesTest < ActiveRecord::TestCase
set_fixture_class :items => Book, :funny_jokes => Joke
set_fixture_class items: Book, funny_jokes: Joke
fixtures :items, :funny_jokes
# Set to false to blow away fixtures cache and ensure our fixtures are loaded
# and thus takes into account our set_fixture_class
@ -593,7 +593,7 @@ def test_named_accessor_of_same_named_fixture
end
class CustomConnectionFixturesTest < ActiveRecord::TestCase
set_fixture_class :courses => Course
set_fixture_class courses: Course
fixtures :courses
self.use_transactional_tests = false
@ -608,7 +608,7 @@ def test_it_twice_in_whatever_order_to_check_for_fixture_leakage
end
class TransactionalFixturesOnCustomConnectionTest < ActiveRecord::TestCase
set_fixture_class :courses => Course
set_fixture_class courses: Course
fixtures :courses
self.use_transactional_tests = true
@ -627,7 +627,7 @@ class TransactionalFixturesOnConnectionNotification < ActiveRecord::TestCase
self.use_instantiated_fixtures = false
def test_transaction_created_on_connection_notification
connection = stub(:transaction_open? => false)
connection = stub(transaction_open?: false)
connection.expects(:begin_transaction).with(joinable: false)
fire_connection_notification(connection)
end
@ -676,7 +676,7 @@ def test_raises_error
end
class CheckEscapedYamlFixturesTest < ActiveRecord::TestCase
set_fixture_class :funny_jokes => Joke
set_fixture_class funny_jokes: Joke
fixtures :funny_jokes
# Set to false to blow away fixtures cache and ensure our fixtures are loaded
# and thus takes into account our set_fixture_class

@ -4,8 +4,8 @@
class HabtmDestroyOrderTest < ActiveRecord::TestCase
test "may not delete a lesson with students" do
sicp = Lesson.new(:name => "SICP")
ben = Student.new(:name => "Ben Bitdiddle")
sicp = Lesson.new(name: "SICP")
ben = Student.new(name: "Ben Bitdiddle")
sicp.students << ben
sicp.save!
assert_raises LessonError do
@ -17,8 +17,8 @@ class HabtmDestroyOrderTest < ActiveRecord::TestCase
end
test "should not raise error if have foreign key in the join table" do
student = Student.new(:name => "Ben Bitdiddle")
lesson = Lesson.new(:name => "SICP")
student = Student.new(name: "Ben Bitdiddle")
lesson = Lesson.new(name: "SICP")
lesson.students << student
lesson.save!
assert_nothing_raised do
@ -29,8 +29,8 @@ class HabtmDestroyOrderTest < ActiveRecord::TestCase
test "not destroying a student with lessons leaves student<=>lesson association intact" do
# test a normal before_destroy doesn't destroy the habtm joins
begin
sicp = Lesson.new(:name => "SICP")
ben = Student.new(:name => "Ben Bitdiddle")
sicp = Lesson.new(name: "SICP")
ben = Student.new(name: "Ben Bitdiddle")
# add a before destroy to student
Student.class_eval do
before_destroy do
@ -49,8 +49,8 @@ class HabtmDestroyOrderTest < ActiveRecord::TestCase
test "not destroying a lesson with students leaves student<=>lesson association intact" do
# test a more aggressive before_destroy doesn't destroy the habtm joins and still throws the exception
sicp = Lesson.new(:name => "SICP")
ben = Student.new(:name => "Ben Bitdiddle")
sicp = Lesson.new(name: "SICP")
ben = Student.new(name: "Ben Bitdiddle")
sicp.students << ben
sicp.save!
assert_raises LessonError do

@ -9,37 +9,37 @@ def setup
end
def test_translated_model_attributes
I18n.backend.store_translations "en", :activerecord => {:attributes => {:topic => {:title => "topic title attribute"} } }
I18n.backend.store_translations "en", activerecord: {attributes: {topic: {title: "topic title attribute"} } }
assert_equal "topic title attribute", Topic.human_attribute_name("title")
end
def test_translated_model_attributes_with_symbols
I18n.backend.store_translations "en", :activerecord => {:attributes => {:topic => {:title => "topic title attribute"} } }
I18n.backend.store_translations "en", activerecord: {attributes: {topic: {title: "topic title attribute"} } }
assert_equal "topic title attribute", Topic.human_attribute_name(:title)
end
def test_translated_model_attributes_with_sti
I18n.backend.store_translations "en", :activerecord => {:attributes => {:reply => {:title => "reply title attribute"} } }
I18n.backend.store_translations "en", activerecord: {attributes: {reply: {title: "reply title attribute"} } }
assert_equal "reply title attribute", Reply.human_attribute_name("title")
end
def test_translated_model_attributes_with_sti_fallback
I18n.backend.store_translations "en", :activerecord => {:attributes => {:topic => {:title => "topic title attribute"} } }
I18n.backend.store_translations "en", activerecord: {attributes: {topic: {title: "topic title attribute"} } }
assert_equal "topic title attribute", Reply.human_attribute_name("title")
end
def test_translated_model_names
I18n.backend.store_translations "en", :activerecord => {:models => {:topic => "topic model"} }
I18n.backend.store_translations "en", activerecord: {models: {topic: "topic model"} }
assert_equal "topic model", Topic.model_name.human
end
def test_translated_model_names_with_sti
I18n.backend.store_translations "en", :activerecord => {:models => {:reply => "reply model"} }
I18n.backend.store_translations "en", activerecord: {models: {reply: "reply model"} }
assert_equal "reply model", Reply.model_name.human
end
def test_translated_model_names_with_sti_fallback
I18n.backend.store_translations "en", :activerecord => {:models => {:topic => "topic model"} }
I18n.backend.store_translations "en", activerecord: {models: {topic: "topic model"} }
assert_equal "topic model", Reply.model_name.human
end
end

@ -229,13 +229,13 @@ def test_alt_becomes_bang_resets_inheritance_type_column
end
def test_inheritance_find_all
companies = Company.all.merge!(:order => "id").to_a
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
def test_alt_inheritance_find_all
companies = Vegetable.all.merge!(:order => "id").to_a
companies = Vegetable.all.merge!(order: "id").to_a
assert_kind_of Cucumber, companies[0]
assert_kind_of Cabbage, companies[1]
end
@ -250,7 +250,7 @@ def test_inheritance_save
end
def test_alt_inheritance_save
cabbage = Cabbage.new(:name => "Savoy")
cabbage = Cabbage.new(name: "Savoy")
cabbage.save!
savoy = Vegetable.find(cabbage.id)
@ -263,12 +263,12 @@ def test_inheritance_new_with_default_class
end
def test_inheritance_new_with_base_class
company = Company.new(:type => "Company")
company = Company.new(type: "Company")
assert_equal Company, company.class
end
def test_inheritance_new_with_subclass
firm = Company.new(:type => "Firm")
firm = Company.new(type: "Firm")
assert_equal Firm, firm.class
end
@ -287,11 +287,11 @@ def test_new_with_ar_base
end
def test_new_with_invalid_type
assert_raise(ActiveRecord::SubclassNotFound) { Company.new(:type => "InvalidType") }
assert_raise(ActiveRecord::SubclassNotFound) { Company.new(type: "InvalidType") }
end
def test_new_with_unrelated_type
assert_raise(ActiveRecord::SubclassNotFound) { Company.new(:type => "Account") }
assert_raise(ActiveRecord::SubclassNotFound) { Company.new(type: "Account") }
end
def test_new_with_unrelated_namespaced_type
@ -319,7 +319,7 @@ def test_new_with_autoload_paths
path = File.expand_path("../../models/autoloadable", __FILE__)
ActiveSupport::Dependencies.autoload_paths << path
firm = Company.new(:type => "ExtraFirm")
firm = Company.new(type: "ExtraFirm")
assert_equal ExtraFirm, firm.class
ensure
ActiveSupport::Dependencies.autoload_paths.reject! { |p| p == path }
@ -352,7 +352,7 @@ def test_update_all_within_inheritance
Client.update_all "name = 'I am a client'"
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.all.merge!(:order => "id").to_a.first.name
assert_equal "37signals", Firm.all.merge!(order: "id").to_a.first.name
end
def test_alt_update_all_within_inheritance
@ -374,51 +374,51 @@ def test_alt_destroy_all_within_inheritance
end
def test_find_first_within_inheritance
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
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
assert_kind_of Cabbage, Vegetable.all.merge!(:where => "name = 'his cabbage'").first
assert_kind_of Cabbage, Cabbage.all.merge!(:where => "name = 'his cabbage'").first
assert_nil Cucumber.all.merge!(:where => "name = 'his cabbage'").first
assert_kind_of Cabbage, Vegetable.all.merge!(where: "name = 'his cabbage'").first
assert_kind_of Cabbage, Cabbage.all.merge!(where: "name = 'his cabbage'").first
assert_nil Cucumber.all.merge!(where: "name = 'his cabbage'").first
end
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.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, 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
def test_alt_complex_inheritance
king_cole = KingCole.create("name" => "uniform heads")
assert_equal king_cole, KingCole.where("name = 'uniform heads'").first
assert_equal king_cole, GreenCabbage.all.merge!(:where => "name = 'uniform heads'").first
assert_equal king_cole, Cabbage.all.merge!(:where => "name = 'uniform heads'").first
assert_equal king_cole, Vegetable.all.merge!(:where => "name = 'uniform heads'").first
assert_equal 1, Cabbage.all.merge!(:where => "name = 'his cabbage'").to_a.size
assert_equal king_cole, GreenCabbage.all.merge!(where: "name = 'uniform heads'").first
assert_equal king_cole, Cabbage.all.merge!(where: "name = 'uniform heads'").first
assert_equal king_cole, Vegetable.all.merge!(where: "name = 'uniform heads'").first
assert_equal 1, Cabbage.all.merge!(where: "name = 'his cabbage'").to_a.size
assert_equal king_cole, Cabbage.find(king_cole.id)
end
def test_eager_load_belongs_to_something_inherited
account = Account.all.merge!(:includes => :firm).find(1)
account = Account.all.merge!(includes: :firm).find(1)
assert account.association(:firm).loaded?, "association was not eager loaded"
end
def test_alt_eager_loading
cabbage = RedCabbage.all.merge!(:includes => :seller).find(4)
cabbage = RedCabbage.all.merge!(includes: :seller).find(4)
assert cabbage.association(:seller).loaded?, "association was not eager loaded"
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')} = 1/) do
Account.all.merge!(:includes => :firm).find(1)
Account.all.merge!(includes: :firm).find(1)
end
end
@ -471,7 +471,7 @@ def test_instantiation_doesnt_try_to_require_corresponding_file
def test_sti_type_from_attributes_disabled_in_non_sti_class
phone = Shop::Product::Type.new(name: "Phone")
product = Shop::Product.new(:type => phone)
product = Shop::Product.new(type: phone)
assert product.save
end

@ -27,12 +27,12 @@ class NamespacedContact < Contact
def setup
@contact = Contact.new(
:name => "Konata Izumi",
:age => 16,
:avatar => "binarydata",
:created_at => Time.utc(2006, 8, 1),
:awesome => true,
:preferences => { :shows => "anime" }
name: "Konata Izumi",
age: 16,
avatar: "binarydata",
created_at: Time.utc(2006, 8, 1),
awesome: true,
preferences: { shows: "anime" }
)
end
@ -68,7 +68,7 @@ def test_should_encode_all_encodable_attributes
end
def test_should_allow_attribute_filtering_with_only
json = @contact.to_json(:only => [:name, :age])
json = @contact.to_json(only: [:name, :age])
assert_match %r{"name":"Konata Izumi"}, json
assert_match %r{"age":16}, json
@ -78,7 +78,7 @@ def test_should_allow_attribute_filtering_with_only
end
def test_should_allow_attribute_filtering_with_except
json = @contact.to_json(:except => [:name, :age])
json = @contact.to_json(except: [:name, :age])
assert_no_match %r{"name":"Konata Izumi"}, json
assert_no_match %r{"age":16}, json
@ -93,10 +93,10 @@ def @contact.label; "Has cheezburger"; end
def @contact.favorite_quote; "Constraints are liberating"; end
# Single method.
assert_match %r{"label":"Has cheezburger"}, @contact.to_json(:only => :name, :methods => :label)
assert_match %r{"label":"Has cheezburger"}, @contact.to_json(only: :name, methods: :label)
# Both methods.
methods_json = @contact.to_json(:only => :name, :methods => [:label, :favorite_quote])
methods_json = @contact.to_json(only: :name, methods: [:label, :favorite_quote])
assert_match %r{"label":"Has cheezburger"}, methods_json
assert_match %r{"favorite_quote":"Constraints are liberating"}, methods_json
end
@ -149,7 +149,7 @@ def @contact.serializable_hash(options={})
end
def test_serializable_hash_should_not_modify_options_in_argument
options = { :only => :name }
options = { only: :name }
@contact.serializable_hash(options)
assert_nil options[:except]
@ -167,7 +167,7 @@ def setup
end
def test_includes_uses_association_name
json = @david.to_json(:include => :posts)
json = @david.to_json(include: :posts)
assert_match %r{"posts":\[}, json
@ -183,7 +183,7 @@ def test_includes_uses_association_name
end
def test_includes_uses_association_name_and_applies_attribute_filters
json = @david.to_json(:include => { :posts => { :only => :title } })
json = @david.to_json(include: { posts: { only: :title } })
assert_match %r{"name":"David"}, json
assert_match %r{"posts":\[}, json
@ -196,7 +196,7 @@ def test_includes_uses_association_name_and_applies_attribute_filters
end
def test_includes_fetches_second_level_associations
json = @david.to_json(:include => { :posts => { :include => { :comments => { :only => :body } } } })
json = @david.to_json(include: { posts: { include: { comments: { only: :body } } } })
assert_match %r{"name":"David"}, json
assert_match %r{"posts":\[}, json
@ -209,12 +209,12 @@ def test_includes_fetches_second_level_associations
def test_includes_fetches_nth_level_associations
json = @david.to_json(
:include => {
:posts => {
:include => {
:taggings => {
:include => {
:tag => { :only => :name }
include: {
posts: {
include: {
taggings: {
include: {
tag: { only: :name }
}
}
}
@ -230,8 +230,8 @@ def test_includes_fetches_nth_level_associations
def test_includes_doesnt_merge_opts_from_base
json = @david.to_json(
:only => :id,
:include => :posts
only: :id,
include: :posts
)
assert_match %{"title":"Welcome to the weblog"}, json
@ -239,7 +239,7 @@ def test_includes_doesnt_merge_opts_from_base
def test_should_not_call_methods_on_associations_that_dont_respond
def @david.favorite_quote; "Constraints are liberating"; end
json = @david.to_json(:include => :posts, :methods => :favorite_quote)
json = @david.to_json(include: :posts, methods: :favorite_quote)
assert !@david.posts.first.respond_to?(:favorite_quote)
assert_match %r{"favorite_quote":"Constraints are liberating"}, json
@ -267,9 +267,9 @@ def test_should_allow_except_option_for_list_of_authors
def test_should_allow_includes_for_list_of_authors
authors = [@david, @mary]
json = ActiveSupport::JSON.encode(authors,
:only => :name,
:include => {
:posts => { :only => :id }
only: :name,
include: {
posts: { only: :id }
}
)

@ -125,7 +125,7 @@ def test_lock_repeating
end
def test_lock_new
p1 = Person.new(:first_name => "anika")
p1 = Person.new(first_name: "anika")
assert_equal 0, p1.lock_version
p1.first_name = "anika2"
@ -144,7 +144,7 @@ def test_lock_new
end
def test_lock_exception_record
p1 = Person.new(:first_name => "mira")
p1 = Person.new(first_name: "mira")
assert_equal 0, p1.lock_version
p1.first_name = "mira2"
@ -162,7 +162,7 @@ def test_lock_exception_record
end
def test_lock_new_with_nil
p1 = Person.new(:first_name => "anika")
p1 = Person.new(first_name: "anika")
p1.save!
p1.lock_version = nil # simulate bad fixture or column with no default
p1.save!
@ -170,7 +170,7 @@ def test_lock_new_with_nil
end
def test_lock_new_when_explicitly_passing_nil
p1 = Person.new(:first_name => "anika", lock_version: nil)
p1 = Person.new(first_name: "anika", lock_version: nil)
p1.save!
assert_equal 0, p1.lock_version
end
@ -209,7 +209,7 @@ def test_lock_column_name_existing
end
def test_lock_column_is_mass_assignable
p1 = Person.create(:first_name => "bianca")
p1 = Person.create(first_name: "bianca")
assert_equal 0, p1.lock_version
assert_equal p1.lock_version, Person.new(p1.attributes).lock_version
@ -242,7 +242,7 @@ def test_lock_with_custom_column_without_default_sets_version_to_zero
def test_readonly_attributes
assert_equal Set.new([ "name" ]), ReadonlyNameShip.readonly_attributes
s = ReadonlyNameShip.create(:name => "unchangeable name")
s = ReadonlyNameShip.create(name: "unchangeable name")
s.reload
assert_equal "unchangeable name", s.name
@ -261,7 +261,7 @@ def test_quote_table_name
# is nothing else being updated.
def test_update_without_attributes_does_not_only_update_lock_version
assert_nothing_raised do
p1 = Person.create!(:first_name => "anika")
p1 = Person.create!(first_name: "anika")
lock_version = p1.lock_version
p1.save
p1.reload
@ -306,7 +306,7 @@ class OptimisticLockingWithSchemaChangeTest < ActiveRecord::TestCase
# of a test (see test_increment_counter_*).
self.use_transactional_tests = false
{ :lock_version => Person, :custom_lock_version => LegacyThing }.each do |name, model|
{ lock_version: Person, custom_lock_version: LegacyThing }.each do |name, model|
define_method("test_increment_counter_updates_#{name}") do
counter_test model, 1 do |id|
model.increment_counter :test_count, id
@ -321,7 +321,7 @@ class OptimisticLockingWithSchemaChangeTest < ActiveRecord::TestCase
define_method("test_update_counters_updates_#{name}") do
counter_test model, 1 do |id|
model.update_counters id, :test_count => 1
model.update_counters id, test_count: 1
end
end
end
@ -333,9 +333,9 @@ def test_destroy_dependents
PersonalLegacyThing.reset_column_information
# Make sure that counter incrementing doesn't cause problems
p1 = Person.new(:first_name => "fjord")
p1 = Person.new(first_name: "fjord")
p1.save!
t = PersonalLegacyThing.new(:person => p1)
t = PersonalLegacyThing.new(person: p1)
t.save!
p1.reload
assert_equal 1, p1.personal_legacy_things_count
@ -351,7 +351,7 @@ def test_destroy_dependents
private
def add_counter_column_to(model, col="test_count")
model.connection.add_column model.table_name, col, :integer, :null => false, :default => 0
model.connection.add_column model.table_name, col, :integer, null: false, default: 0
model.reset_column_information
end

@ -40,7 +40,7 @@ def test_create_table_adds_id
def test_create_table_with_not_null_column
connection.create_table :testings do |t|
t.column :foo, :string, :null => false
t.column :foo, :string, null: false
end
assert_raises(ActiveRecord::StatementInvalid) do
@ -53,11 +53,11 @@ def test_create_table_with_defaults
mysql = current_adapter?(:Mysql2Adapter)
connection.create_table :testings do |t|
t.column :one, :string, :default => "hello"
t.column :two, :boolean, :default => true
t.column :three, :boolean, :default => false
t.column :four, :integer, :default => 1
t.column :five, :text, :default => "hello" unless mysql
t.column :one, :string, default: "hello"
t.column :two, :boolean, default: true
t.column :three, :boolean, default: false
t.column :four, :integer, default: 1
t.column :five, :text, default: "hello" unless mysql
end
columns = connection.columns(:testings)
@ -77,7 +77,7 @@ def test_create_table_with_defaults
if current_adapter?(:PostgreSQLAdapter)
def test_add_column_with_array
connection.create_table :testings
connection.add_column :testings, :foo, :string, :array => true
connection.add_column :testings, :foo, :string, array: true
columns = connection.columns(:testings)
array_column = columns.detect { |c| c.name == "foo" }
@ -87,7 +87,7 @@ def test_add_column_with_array
def test_create_table_with_array_column
connection.create_table :testings do |t|
t.string :foo, :array => true
t.string :foo, array: true
end
columns = connection.columns(:testings)
@ -118,13 +118,13 @@ def test_create_table_with_bigint
def test_create_table_with_limits
connection.create_table :testings do |t|
t.column :foo, :string, :limit => 255
t.column :foo, :string, limit: 255
t.column :default_int, :integer
t.column :one_int, :integer, :limit => 1
t.column :four_int, :integer, :limit => 4
t.column :eight_int, :integer, :limit => 8
t.column :one_int, :integer, limit: 1
t.column :four_int, :integer, limit: 4
t.column :eight_int, :integer, limit: 8
end
columns = connection.columns(:testings)
@ -231,7 +231,7 @@ def test_add_column_not_null_without_default
connection.create_table :testings do |t|
t.column :foo, :string
end
connection.add_column :testings, :bar, :string, :null => false
connection.add_column :testings, :bar, :string, null: false
assert_raise(ActiveRecord::StatementInvalid) do
connection.execute "insert into testings (foo, bar) values ('hello', NULL)"
@ -246,7 +246,7 @@ def test_add_column_not_null_with_default
con = connection
connection.execute "insert into testings (#{con.quote_column_name('id')}, #{con.quote_column_name('foo')}) values (1, 'hello')"
assert_nothing_raised {connection.add_column :testings, :bar, :string, :null => false, :default => "default" }
assert_nothing_raised {connection.add_column :testings, :bar, :string, null: false, default: "default" }
assert_raises(ActiveRecord::StatementInvalid) do
connection.execute "insert into testings (#{con.quote_column_name('id')}, #{con.quote_column_name('foo')}, #{con.quote_column_name('bar')}) values (2, 'hello', NULL)"
@ -275,7 +275,7 @@ def test_change_column_quotes_column_names
t.column :select, :string
end
connection.change_column :testings, :select, :string, :limit => 10
connection.change_column :testings, :select, :string, limit: 10
# Oracle needs primary key value from sequence
if current_adapter?(:OracleAdapter)
@ -292,7 +292,7 @@ def test_keeping_default_and_notnull_constraints_on_change
person_klass = Class.new(ActiveRecord::Base)
person_klass.table_name = "testings"
person_klass.connection.add_column "testings", "wealth", :integer, :null => false, :default => 99
person_klass.connection.add_column "testings", "wealth", :integer, null: false, default: 99
person_klass.reset_column_information
assert_equal 99, person_klass.column_defaults["wealth"]
assert_equal false, person_klass.columns_hash["wealth"].null
@ -317,13 +317,13 @@ def test_keeping_default_and_notnull_constraints_on_change
assert_equal false, person_klass.columns_hash["money"].null
# change column
person_klass.connection.change_column "testings", "money", :integer, :null => false, :default => 1000
person_klass.connection.change_column "testings", "money", :integer, null: false, default: 1000
person_klass.reset_column_information
assert_equal 1000, person_klass.column_defaults["money"]
assert_equal false, person_klass.columns_hash["money"].null
# change column, make it nullable and clear default
person_klass.connection.change_column "testings", "money", :integer, :null => true, :default => nil
person_klass.connection.change_column "testings", "money", :integer, null: true, default: nil
person_klass.reset_column_information
assert_nil person_klass.columns_hash["money"].default
assert_equal true, person_klass.columns_hash["money"].null
@ -365,7 +365,7 @@ def test_column_exists
def test_column_exists_with_type
connection.create_table :testings do |t|
t.column :foo, :string
t.column :bar, :decimal, :precision => 8, :scale => 2
t.column :bar, :decimal, precision: 8, scale: 2
end
assert connection.column_exists?(:testings, :foo, :string)
@ -416,7 +416,7 @@ def test_drop_table_if_exists_nothing_raised
private
def testing_table_with_only_foo_attribute
connection.create_table :testings, :id => false do |t|
connection.create_table :testings, id: false do |t|
t.column :foo, :string
end

@ -157,8 +157,8 @@ def test_column_creates_column
def test_column_creates_column_with_options
with_change_table do |t|
@connection.expect :add_column, nil, [:delete_me, :bar, :integer, {:null => false}]
t.column :bar, :integer, :null => false
@connection.expect :add_column, nil, [:delete_me, :bar, :integer, {null: false}]
t.column :bar, :integer, null: false
end
end
@ -171,8 +171,8 @@ def test_index_creates_index
def test_index_creates_index_with_options
with_change_table do |t|
@connection.expect :add_index, nil, [:delete_me, :bar, {:unique => true}]
t.index :bar, :unique => true
@connection.expect :add_index, nil, [:delete_me, :bar, {unique: true}]
t.index :bar, unique: true
end
end
@ -185,8 +185,8 @@ def test_index_exists
def test_index_exists_with_options
with_change_table do |t|
@connection.expect :index_exists?, nil, [:delete_me, :bar, {:unique => true}]
t.index_exists?(:bar, :unique => true)
@connection.expect :index_exists?, nil, [:delete_me, :bar, {unique: true}]
t.index_exists?(:bar, unique: true)
end
end
@ -206,8 +206,8 @@ def test_change_changes_column
def test_change_changes_column_with_options
with_change_table do |t|
@connection.expect :change_column, nil, [:delete_me, :bar, :string, {:null => true}]
t.change :bar, :string, :null => true
@connection.expect :change_column, nil, [:delete_me, :bar, :string, {null: true}]
t.change :bar, :string, null: true
end
end
@ -234,8 +234,8 @@ def test_remove_drops_multiple_columns
def test_remove_index_removes_index_with_options
with_change_table do |t|
@connection.expect :remove_index, nil, [:delete_me, {:unique => true}]
t.remove_index :unique => true
@connection.expect :remove_index, nil, [:delete_me, {unique: true}]
t.remove_index unique: true
end
end

@ -9,7 +9,7 @@ class ColumnAttributesTest < ActiveRecord::TestCase
def test_add_column_newline_default
string = "foo\nbar"
add_column "test_models", "command", :string, :default => string
add_column "test_models", "command", :string, default: string
TestModel.reset_column_information
assert_equal string, TestModel.new.command
@ -58,7 +58,7 @@ def test_unabstracted_database_dependent_types
def test_native_decimal_insert_manual_vs_automatic
correct_value = "0012345678901234567890.0123456789".to_d
connection.add_column "test_models", "wealth", :decimal, :precision => "30", :scale => "10"
connection.add_column "test_models", "wealth", :decimal, precision: "30", scale: "10"
# Do a manual insertion
if current_adapter?(:OracleAdapter)
@ -82,7 +82,7 @@ def test_native_decimal_insert_manual_vs_automatic
TestModel.delete_all
# Now use the Rails insertion
TestModel.create :wealth => BigDecimal.new("12345678901234567890.0123456789")
TestModel.create wealth: BigDecimal.new("12345678901234567890.0123456789")
# SELECT
row = TestModel.first
@ -94,7 +94,7 @@ def test_native_decimal_insert_manual_vs_automatic
end
def test_add_column_with_precision_and_scale
connection.add_column "test_models", "wealth", :decimal, :precision => 9, :scale => 7
connection.add_column "test_models", "wealth", :decimal, precision: 9, scale: 7
wealth_column = TestModel.columns_hash["wealth"]
assert_equal 9, wealth_column.precision
@ -104,13 +104,13 @@ def test_add_column_with_precision_and_scale
if current_adapter?(:SQLite3Adapter)
def test_change_column_preserve_other_column_precision_and_scale
connection.add_column "test_models", "last_name", :string
connection.add_column "test_models", "wealth", :decimal, :precision => 9, :scale => 7
connection.add_column "test_models", "wealth", :decimal, precision: 9, scale: 7
wealth_column = TestModel.columns_hash["wealth"]
assert_equal 9, wealth_column.precision
assert_equal 7, wealth_column.scale
connection.change_column "test_models", "last_name", :string, :null => false
connection.change_column "test_models", "last_name", :string, null: false
TestModel.reset_column_information
wealth_column = TestModel.columns_hash["wealth"]
@ -126,17 +126,17 @@ def test_native_types
add_column "test_models", "bio", :text
add_column "test_models", "age", :integer
add_column "test_models", "height", :float
add_column "test_models", "wealth", :decimal, :precision => "30", :scale => "10"
add_column "test_models", "wealth", :decimal, precision: "30", scale: "10"
add_column "test_models", "birthday", :datetime
add_column "test_models", "favorite_day", :date
add_column "test_models", "moment_of_truth", :datetime
add_column "test_models", "male", :boolean
TestModel.create :first_name => "bob", :last_name => "bobsen",
:bio => "I was born ....", :age => 18, :height => 1.78,
:wealth => BigDecimal.new("12345678901234567890.0123456789"),
:birthday => 18.years.ago, :favorite_day => 10.days.ago,
:moment_of_truth => "1782-10-10 21:40:18", :male => true
TestModel.create first_name: "bob", last_name: "bobsen",
bio: "I was born ....", age: 18, height: 1.78,
wealth: BigDecimal.new("12345678901234567890.0123456789"),
birthday: 18.years.ago, favorite_day: 10.days.ago,
moment_of_truth: "1782-10-10 21:40:18", male: true
bob = TestModel.first
assert_equal "bob", bob.first_name
@ -164,10 +164,10 @@ def test_native_types
if current_adapter?(:Mysql2Adapter, :PostgreSQLAdapter)
def test_out_of_range_limit_should_raise
assert_raise(ActiveRecordError) { add_column :test_models, :integer_too_big, :integer, :limit => 10 }
assert_raise(ActiveRecordError) { add_column :test_models, :integer_too_big, :integer, limit: 10 }
unless current_adapter?(:PostgreSQLAdapter)
assert_raise(ActiveRecordError) { add_column :test_models, :text_too_big, :integer, :limit => 0xfffffffff }
assert_raise(ActiveRecordError) { add_column :test_models, :text_too_big, :integer, limit: 0xfffffffff }
end
end
end

@ -11,7 +11,7 @@ def setup
@connection = ActiveRecord::Base.connection
connection.create_table :testings, :id => false do |t|
connection.create_table :testings, id: false do |t|
t.column :first, :integer
t.column :second, :integer
t.column :third, :integer
@ -34,20 +34,20 @@ def test_add_column_with_positioning
end
def test_add_column_with_positioning_first
conn.add_column :testings, :new_col, :integer, :first => true
conn.add_column :testings, :new_col, :integer, first: true
assert_equal %w(new_col first second third), conn.columns(:testings).map(&:name)
end
def test_add_column_with_positioning_after
conn.add_column :testings, :new_col, :integer, :after => :first
conn.add_column :testings, :new_col, :integer, after: :first
assert_equal %w(first new_col second third), conn.columns(:testings).map(&:name)
end
def test_change_column_with_positioning
conn.change_column :testings, :second, :integer, :first => true
conn.change_column :testings, :second, :integer, first: true
assert_equal %w(second first third), conn.columns(:testings).map(&:name)
conn.change_column :testings, :second, :integer, :after => :third
conn.change_column :testings, :second, :integer, after: :third
assert_equal %w(first third second), conn.columns(:testings).map(&:name)
end
end

@ -13,7 +13,7 @@ def test_add_rename
add_column "test_models", "girlfriend", :string
TestModel.reset_column_information
TestModel.create :girlfriend => "bobette"
TestModel.create girlfriend: "bobette"
rename_column "test_models", "girlfriend", "exgirlfriend"
@ -28,7 +28,7 @@ def test_add_rename
def test_rename_column_using_symbol_arguments
add_column :test_models, :first_name, :string
TestModel.create :first_name => "foo"
TestModel.create first_name: "foo"
rename_column :test_models, :first_name, :nick_name
TestModel.reset_column_information
@ -41,7 +41,7 @@ def test_rename_column_using_symbol_arguments
def test_rename_column
add_column "test_models", "first_name", "string"
TestModel.create :first_name => "foo"
TestModel.create first_name: "foo"
rename_column "test_models", "first_name", "nick_name"
TestModel.reset_column_information
@ -50,7 +50,7 @@ def test_rename_column
end
def test_rename_column_preserves_default_value_not_null
add_column "test_models", "salary", :integer, :default => 70000
add_column "test_models", "salary", :integer, default: 70000
default_before = connection.columns("test_models").find { |c| c.name == "salary" }.default
assert_equal "70000", default_before
@ -122,7 +122,7 @@ def test_rename_column_with_multi_column_index
def test_rename_column_does_not_rename_custom_named_index
add_column "test_models", :hat_name, :string
add_index :test_models, :hat_name, :name => "idx_hat_name"
add_index :test_models, :hat_name, name: "idx_hat_name"
assert_equal 1, connection.indexes("test_models").size
rename_column "test_models", "hat_name", "name"
@ -140,8 +140,8 @@ def test_remove_column_with_index
def test_remove_column_with_multi_column_index
add_column "test_models", :hat_size, :integer
add_column "test_models", :hat_style, :string, :limit => 100
add_index "test_models", ["hat_style", "hat_size"], :unique => true
add_column "test_models", :hat_style, :string, limit: 100
add_index "test_models", ["hat_style", "hat_size"], unique: true
assert_equal 1, connection.indexes("test_models").size
remove_column("test_models", "hat_size")
@ -156,32 +156,32 @@ def test_remove_column_with_multi_column_index
end
def test_change_type_of_not_null_column
change_column "test_models", "updated_at", :datetime, :null => false
change_column "test_models", "updated_at", :datetime, :null => false
change_column "test_models", "updated_at", :datetime, null: false
change_column "test_models", "updated_at", :datetime, null: false
TestModel.reset_column_information
assert_equal false, TestModel.columns_hash["updated_at"].null
ensure
change_column "test_models", "updated_at", :datetime, :null => true
change_column "test_models", "updated_at", :datetime, null: true
end
def test_change_column_nullability
add_column "test_models", "funny", :boolean
assert TestModel.columns_hash["funny"].null, "Column 'funny' must initially allow nulls"
change_column "test_models", "funny", :boolean, :null => false, :default => true
change_column "test_models", "funny", :boolean, null: false, default: true
TestModel.reset_column_information
assert_not TestModel.columns_hash["funny"].null, "Column 'funny' must *not* allow nulls at this point"
change_column "test_models", "funny", :boolean, :null => true
change_column "test_models", "funny", :boolean, null: true
TestModel.reset_column_information
assert TestModel.columns_hash["funny"].null, "Column 'funny' must allow nulls again at this point"
end
def test_change_column
add_column "test_models", "age", :integer
add_column "test_models", "approved", :boolean, :default => true
add_column "test_models", "approved", :boolean, default: true
old_columns = connection.columns(TestModel.table_name)
@ -200,7 +200,7 @@ def test_change_column
c.name == "approved" && c.type == :boolean && default == true
}
change_column :test_models, :approved, :boolean, :default => false
change_column :test_models, :approved, :boolean, default: false
new_columns = connection.columns(TestModel.table_name)
assert_not new_columns.find { |c|
@ -211,24 +211,24 @@ def test_change_column
default = connection.lookup_cast_type_from_column(c).deserialize(c.default)
c.name == "approved" and c.type == :boolean and default == false
}
change_column :test_models, :approved, :boolean, :default => true
change_column :test_models, :approved, :boolean, default: true
end
def test_change_column_with_nil_default
add_column "test_models", "contributor", :boolean, :default => true
add_column "test_models", "contributor", :boolean, default: true
assert TestModel.new.contributor?
change_column "test_models", "contributor", :boolean, :default => nil
change_column "test_models", "contributor", :boolean, default: nil
TestModel.reset_column_information
assert_not TestModel.new.contributor?
assert_nil TestModel.new.contributor
end
def test_change_column_with_new_default
add_column "test_models", "administrator", :boolean, :default => true
add_column "test_models", "administrator", :boolean, default: true
assert TestModel.new.administrator?
change_column "test_models", "administrator", :boolean, :default => false
change_column "test_models", "administrator", :boolean, default: false
TestModel.reset_column_information
assert_not TestModel.new.administrator?
end

@ -13,8 +13,8 @@ def setup
ActiveRecord::Migration.verbose = false
connection.create_table :testings do |t|
t.column :foo, :string, :limit => 100
t.column :bar, :string, :limit => 100
t.column :foo, :string, limit: 100
t.column :bar, :string, limit: 100
end
end
@ -25,7 +25,7 @@ def setup
end
def test_migration_doesnt_remove_named_index
connection.add_index :testings, :foo, :name => "custom_index_name"
connection.add_index :testings, :foo, name: "custom_index_name"
migration = Class.new(ActiveRecord::Migration[4.2]) {
def version; 101 end

@ -11,12 +11,12 @@ def setup
@table_name = :testings
connection.create_table table_name do |t|
t.column :foo, :string, :limit => 100
t.column :bar, :string, :limit => 100
t.column :foo, :string, limit: 100
t.column :bar, :string, limit: 100
t.string :first_name
t.string :last_name, :limit => 100
t.string :key, :limit => 100
t.string :last_name, limit: 100
t.string :key, limit: 100
t.boolean :administrator
end
end
@ -28,7 +28,7 @@ def setup
def test_rename_index
# keep the names short to make Oracle and similar behave
connection.add_index(table_name, [:foo], :name => "old_idx")
connection.add_index(table_name, [:foo], name: "old_idx")
connection.rename_index(table_name, "old_idx", "new_idx")
# if the adapter doesn't support the indexes call, pick defaults that let the test pass
@ -39,7 +39,7 @@ def test_rename_index
def test_rename_index_too_long
too_long_index_name = good_index_name + "x"
# keep the names short to make Oracle and similar behave
connection.add_index(table_name, [:foo], :name => "old_idx")
connection.add_index(table_name, [:foo], name: "old_idx")
e = assert_raises(ArgumentError) {
connection.rename_index(table_name, "old_idx", too_long_index_name)
}
@ -51,9 +51,9 @@ def test_rename_index_too_long
def test_double_add_index
connection.add_index(table_name, [:foo], :name => "some_idx")
connection.add_index(table_name, [:foo], name: "some_idx")
assert_raises(ArgumentError) {
connection.add_index(table_name, [:foo], :name => "some_idx")
connection.add_index(table_name, [:foo], name: "some_idx")
}
end
@ -77,7 +77,7 @@ def test_add_index_does_not_accept_too_long_index_names
assert_match(/too long; the limit is #{connection.allowed_index_name_length} characters/, e.message)
assert_not connection.index_name_exists?(table_name, too_long_index_name, false)
connection.add_index(table_name, "foo", :name => good_index_name)
connection.add_index(table_name, "foo", name: good_index_name)
end
def test_internal_index_with_name_matching_database_limit
@ -89,11 +89,11 @@ def test_internal_index_with_name_matching_database_limit
end
def test_index_symbol_names
connection.add_index table_name, :foo, :name => :symbol_index_name
assert connection.index_exists?(table_name, :foo, :name => :symbol_index_name)
connection.add_index table_name, :foo, name: :symbol_index_name
assert connection.index_exists?(table_name, :foo, name: :symbol_index_name)
connection.remove_index table_name, :name => :symbol_index_name
assert_not connection.index_exists?(table_name, :foo, :name => :symbol_index_name)
connection.remove_index table_name, name: :symbol_index_name
assert_not connection.index_exists?(table_name, :foo, name: :symbol_index_name)
end
def test_index_exists
@ -122,21 +122,21 @@ def test_valid_index_options
end
def test_unique_index_exists
connection.add_index :testings, :foo, :unique => true
connection.add_index :testings, :foo, unique: true
assert connection.index_exists?(:testings, :foo, :unique => true)
assert connection.index_exists?(:testings, :foo, unique: true)
end
def test_named_index_exists
connection.add_index :testings, :foo, :name => "custom_index_name"
connection.add_index :testings, :foo, name: "custom_index_name"
assert connection.index_exists?(:testings, :foo)
assert connection.index_exists?(:testings, :foo, :name => "custom_index_name")
assert !connection.index_exists?(:testings, :foo, :name => "other_index_name")
assert connection.index_exists?(:testings, :foo, name: "custom_index_name")
assert !connection.index_exists?(:testings, :foo, name: "other_index_name")
end
def test_remove_named_index
connection.add_index :testings, :foo, :name => "custom_index_name"
connection.add_index :testings, :foo, name: "custom_index_name"
assert connection.index_exists?(:testings, :foo)
connection.remove_index :testings, :foo
@ -144,7 +144,7 @@ def test_remove_named_index
end
def test_add_index_attribute_length_limit
connection.add_index :testings, [:foo, :bar], :length => {:foo => 10, :bar => nil}
connection.add_index :testings, [:foo, :bar], length: {foo: 10, bar: nil}
assert connection.index_exists?(:testings, [:foo, :bar])
end
@ -154,53 +154,53 @@ def test_add_index
connection.remove_index("testings", "last_name")
connection.add_index("testings", ["last_name", "first_name"])
connection.remove_index("testings", :column => ["last_name", "first_name"])
connection.remove_index("testings", column: ["last_name", "first_name"])
# Oracle adapter cannot have specified index name larger than 30 characters
# Oracle adapter is shortening index name when just column list is given
unless current_adapter?(:OracleAdapter)
connection.add_index("testings", ["last_name", "first_name"])
connection.remove_index("testings", :name => :index_testings_on_last_name_and_first_name)
connection.remove_index("testings", name: :index_testings_on_last_name_and_first_name)
connection.add_index("testings", ["last_name", "first_name"])
connection.remove_index("testings", "last_name_and_first_name")
end
connection.add_index("testings", ["last_name", "first_name"])
connection.remove_index("testings", ["last_name", "first_name"])
connection.add_index("testings", ["last_name"], :length => 10)
connection.add_index("testings", ["last_name"], length: 10)
connection.remove_index("testings", "last_name")
connection.add_index("testings", ["last_name"], :length => {:last_name => 10})
connection.add_index("testings", ["last_name"], length: {last_name: 10})
connection.remove_index("testings", ["last_name"])
connection.add_index("testings", ["last_name", "first_name"], :length => 10)
connection.add_index("testings", ["last_name", "first_name"], length: 10)
connection.remove_index("testings", ["last_name", "first_name"])
connection.add_index("testings", ["last_name", "first_name"], :length => {:last_name => 10, :first_name => 20})
connection.add_index("testings", ["last_name", "first_name"], length: {last_name: 10, first_name: 20})
connection.remove_index("testings", ["last_name", "first_name"])
connection.add_index("testings", ["key"], :name => "key_idx", :unique => true)
connection.remove_index("testings", :name => "key_idx", :unique => true)
connection.add_index("testings", ["key"], name: "key_idx", unique: true)
connection.remove_index("testings", name: "key_idx", unique: true)
connection.add_index("testings", %w(last_name first_name administrator), :name => "named_admin")
connection.remove_index("testings", :name => "named_admin")
connection.add_index("testings", %w(last_name first_name administrator), name: "named_admin")
connection.remove_index("testings", name: "named_admin")
# Selected adapters support index sort order
if current_adapter?(:SQLite3Adapter, :Mysql2Adapter, :PostgreSQLAdapter)
connection.add_index("testings", ["last_name"], :order => {:last_name => :desc})
connection.add_index("testings", ["last_name"], order: {last_name: :desc})
connection.remove_index("testings", ["last_name"])
connection.add_index("testings", ["last_name", "first_name"], :order => {:last_name => :desc})
connection.add_index("testings", ["last_name", "first_name"], order: {last_name: :desc})
connection.remove_index("testings", ["last_name", "first_name"])
connection.add_index("testings", ["last_name", "first_name"], :order => {:last_name => :desc, :first_name => :asc})
connection.add_index("testings", ["last_name", "first_name"], order: {last_name: :desc, first_name: :asc})
connection.remove_index("testings", ["last_name", "first_name"])
connection.add_index("testings", ["last_name", "first_name"], :order => :desc)
connection.add_index("testings", ["last_name", "first_name"], order: :desc)
connection.remove_index("testings", ["last_name", "first_name"])
end
end
if current_adapter?(:PostgreSQLAdapter)
def test_add_partial_index
connection.add_index("testings", "last_name", :where => "first_name = 'john doe'")
connection.add_index("testings", "last_name", where: "first_name = 'john doe'")
assert connection.index_exists?("testings", "last_name")
connection.remove_index("testings", "last_name")

@ -17,10 +17,10 @@ def setup
def test_creates_index
connection.create_table table_name do |t|
t.references :foo, :index => true
t.references :foo, index: true
end
assert connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_foo_id)
assert connection.index_exists?(table_name, :foo_id, name: :index_testings_on_foo_id)
end
def test_creates_index_by_default_even_if_index_option_is_not_passed
@ -28,31 +28,31 @@ def test_creates_index_by_default_even_if_index_option_is_not_passed
t.references :foo
end
assert connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_foo_id)
assert connection.index_exists?(table_name, :foo_id, name: :index_testings_on_foo_id)
end
def test_does_not_create_index_explicit
connection.create_table table_name do |t|
t.references :foo, :index => false
t.references :foo, index: false
end
assert_not connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_foo_id)
assert_not connection.index_exists?(table_name, :foo_id, name: :index_testings_on_foo_id)
end
def test_creates_index_with_options
connection.create_table table_name do |t|
t.references :foo, :index => {:name => :index_testings_on_yo_momma}
t.references :bar, :index => {:unique => true}
t.references :foo, index: {name: :index_testings_on_yo_momma}
t.references :bar, index: {unique: true}
end
assert connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_yo_momma)
assert connection.index_exists?(table_name, :bar_id, :name => :index_testings_on_bar_id, :unique => true)
assert connection.index_exists?(table_name, :foo_id, name: :index_testings_on_yo_momma)
assert connection.index_exists?(table_name, :bar_id, name: :index_testings_on_bar_id, unique: true)
end
unless current_adapter? :OracleAdapter
def test_creates_polymorphic_index
connection.create_table table_name do |t|
t.references :foo, :polymorphic => true, :index => true
t.references :foo, polymorphic: true, index: true
end
assert connection.index_exists?(table_name, [:foo_type, :foo_id], name: :index_testings_on_foo_type_and_foo_id)
@ -62,10 +62,10 @@ def test_creates_polymorphic_index
def test_creates_index_for_existing_table
connection.create_table table_name
connection.change_table table_name do |t|
t.references :foo, :index => true
t.references :foo, index: true
end
assert connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_foo_id)
assert connection.index_exists?(table_name, :foo_id, name: :index_testings_on_foo_id)
end
def test_creates_index_for_existing_table_even_if_index_option_is_not_passed
@ -74,23 +74,23 @@ def test_creates_index_for_existing_table_even_if_index_option_is_not_passed
t.references :foo
end
assert connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_foo_id)
assert connection.index_exists?(table_name, :foo_id, name: :index_testings_on_foo_id)
end
def test_does_not_create_index_for_existing_table_explicit
connection.create_table table_name
connection.change_table table_name do |t|
t.references :foo, :index => false
t.references :foo, index: false
end
assert_not connection.index_exists?(table_name, :foo_id, :name => :index_testings_on_foo_id)
assert_not connection.index_exists?(table_name, :foo_id, name: :index_testings_on_foo_id)
end
unless current_adapter? :OracleAdapter
def test_creates_polymorphic_index_for_existing_table
connection.create_table table_name
connection.change_table table_name do |t|
t.references :foo, :polymorphic => true, :index => true
t.references :foo, polymorphic: true, index: true
end
assert connection.index_exists?(table_name, [:foo_type, :foo_id], name: :index_testings_on_foo_type_and_foo_id)

@ -128,7 +128,7 @@ def test_create_table_with_force_true_does_not_drop_nonexisting_table
assert_not_equal temp_conn, Person.connection
temp_conn.create_table :testings2, :force => true do |t|
temp_conn.create_table :testings2, force: true do |t|
t.column :foo, :string
end
ensure
@ -160,11 +160,11 @@ def test_add_table_with_decimals
BigNumber.reset_column_information
assert BigNumber.create(
:bank_balance => 1586.43,
:big_bank_balance => BigDecimal("1000234000567.95"),
:world_population => 6000000000,
:my_house_population => 3,
:value_of_e => BigDecimal("2.7182818284590452353602875")
bank_balance: 1586.43,
big_bank_balance: BigDecimal("1000234000567.95"),
world_population: 6000000000,
my_house_population: 3,
value_of_e: BigDecimal("2.7182818284590452353602875")
)
b = BigNumber.first
@ -514,7 +514,7 @@ def test_add_drop_table_with_prefix_and_suffix
def test_create_table_with_binary_column
assert_nothing_raised {
Person.connection.create_table :binary_testings do |t|
t.column "data", :binary, :null => false
t.column "data", :binary, null: false
end
}
@ -559,7 +559,7 @@ def test_create_table_with_custom_sequence_name
assert_nothing_raised do
begin
Person.connection.create_table :table_with_name_thats_just_ok do |t|
t.column :foo, :string, :null => false
t.column :foo, :string, null: false
end
ensure
Person.connection.drop_table :table_with_name_thats_just_ok rescue nil
@ -570,15 +570,15 @@ def test_create_table_with_custom_sequence_name
assert_nothing_raised do
begin
Person.connection.create_table :table_with_name_thats_just_ok,
:sequence_name => "suitably_short_seq" do |t|
t.column :foo, :string, :null => false
sequence_name: "suitably_short_seq" do |t|
t.column :foo, :string, null: false
end
Person.connection.execute("select suitably_short_seq.nextval from dual")
ensure
Person.connection.drop_table :table_with_name_thats_just_ok,
:sequence_name => "suitably_short_seq" rescue nil
sequence_name: "suitably_short_seq" rescue nil
end
end
@ -592,8 +592,8 @@ def test_create_table_with_custom_sequence_name
if current_adapter?(:Mysql2Adapter, :PostgreSQLAdapter)
def test_out_of_range_integer_limit_should_raise
e = assert_raise(ActiveRecord::ActiveRecordError, "integer limit didn't raise") do
Person.connection.create_table :test_integer_limits, :force => true do |t|
t.column :bigone, :integer, :limit => 10
Person.connection.create_table :test_integer_limits, force: true do |t|
t.column :bigone, :integer, limit: 10
end
end
@ -727,13 +727,13 @@ def with_another_process_holding_lock(lock_id)
class ReservedWordsMigrationTest < ActiveRecord::TestCase
def test_drop_index_from_table_named_values
connection = Person.connection
connection.create_table :values, :force => true do |t|
connection.create_table :values, force: true do |t|
t.integer :value
end
assert_nothing_raised do
connection.add_index :values, :value
connection.remove_index :values, :column => :value
connection.remove_index :values, column: :value
end
ensure
connection.drop_table :values rescue nil
@ -760,7 +760,7 @@ def test_drop_index_by_name
class BulkAlterTableMigrationsTest < ActiveRecord::TestCase
def setup
@connection = Person.connection
@connection.create_table(:delete_me, :force => true) {|t| }
@connection.create_table(:delete_me, force: true) {|t| }
Person.reset_column_information
Person.reset_sequence_name
end
@ -774,7 +774,7 @@ def test_adding_multiple_columns
with_bulk_change_table do |t|
t.column :name, :string
t.string :qualification, :experience
t.integer :age, :default => 0
t.integer :age, default: 0
t.date :birthdate
t.timestamps null: true
end
@ -813,7 +813,7 @@ def test_adding_indexes
# Adding an index fires a query every time to check if an index already exists or not
assert_queries(3) do
with_bulk_change_table do |t|
t.index :username, :unique => true, :name => :awesome_username_index
t.index :username, unique: true, name: :awesome_username_index
t.index [:name, :age]
end
end
@ -838,7 +838,7 @@ def test_removing_index
assert_queries(3) do
with_bulk_change_table do |t|
t.remove_index :name
t.index :name, :name => :new_name_index, :unique => true
t.index :name, name: :new_name_index, unique: true
end
end
@ -860,9 +860,9 @@ def test_changing_columns
# 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, :ignore_none => true) do
assert_queries(3, ignore_none: true) do
with_bulk_change_table do |t|
t.change :name, :string, :default => "NONAME"
t.change :name, :string, default: "NONAME"
t.change :birthdate, :datetime
end
end
@ -877,7 +877,7 @@ def with_bulk_change_table
# Reset columns/indexes cache as we're changing the table
@columns = @indexes = nil
Person.connection.change_table(:delete_me, :bulk => true) do |t|
Person.connection.change_table(:delete_me, bulk: true) do |t|
yield t
end
end
@ -918,7 +918,7 @@ def test_copying_migrations_without_timestamps
@migrations_path = MIGRATIONS_ROOT + "/valid"
@existing_migrations = Dir[@migrations_path + "/*.rb"]
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy"})
copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy"})
assert File.exist?(@migrations_path + "/4_people_have_hobbies.bukkits.rb")
assert File.exist?(@migrations_path + "/5_people_have_descriptions.bukkits.rb")
assert_equal [@migrations_path + "/4_people_have_hobbies.bukkits.rb", @migrations_path + "/5_people_have_descriptions.bukkits.rb"], copied.map(&:filename)
@ -927,7 +927,7 @@ def test_copying_migrations_without_timestamps
assert_equal expected, IO.readlines(@migrations_path + "/4_people_have_hobbies.bukkits.rb")[0].chomp
files_count = Dir[@migrations_path + "/*.rb"].length
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy"})
copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy"})
assert_equal files_count, Dir[@migrations_path + "/*.rb"].length
assert copied.empty?
ensure
@ -960,7 +960,7 @@ def test_copying_migrations_with_timestamps
@existing_migrations = Dir[@migrations_path + "/*.rb"]
travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
assert File.exist?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb")
assert File.exist?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb")
expected = [@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb",
@ -968,7 +968,7 @@ def test_copying_migrations_with_timestamps
assert_equal expected, copied.map(&:filename)
files_count = Dir[@migrations_path + "/*.rb"].length
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
assert_equal files_count, Dir[@migrations_path + "/*.rb"].length
assert copied.empty?
end
@ -1005,12 +1005,12 @@ def test_copying_migrations_with_timestamps_to_destination_with_timestamps_in_fu
@existing_migrations = Dir[@migrations_path + "/*.rb"]
travel_to(Time.utc(2010, 2, 20, 10, 10, 10)) do
ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
assert File.exist?(@migrations_path + "/20100301010102_people_have_hobbies.bukkits.rb")
assert File.exist?(@migrations_path + "/20100301010103_people_have_descriptions.bukkits.rb")
files_count = Dir[@migrations_path + "/*.rb"].length
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
assert_equal files_count, Dir[@migrations_path + "/*.rb"].length
assert copied.empty?
end
@ -1023,7 +1023,7 @@ def test_copying_migrations_preserving_magic_comments
@migrations_path = MIGRATIONS_ROOT + "/valid"
@existing_migrations = Dir[@migrations_path + "/*.rb"]
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/magic"})
copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/magic"})
assert File.exist?(@migrations_path + "/4_currencies_have_symbols.bukkits.rb")
assert_equal [@migrations_path + "/4_currencies_have_symbols.bukkits.rb"], copied.map(&:filename)
@ -1031,7 +1031,7 @@ def test_copying_migrations_preserving_magic_comments
assert_equal expected, IO.readlines(@migrations_path + "/4_currencies_have_symbols.bukkits.rb")[0..1].join.chomp
files_count = Dir[@migrations_path + "/*.rb"].length
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/magic"})
copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/magic"})
assert_equal files_count, Dir[@migrations_path + "/*.rb"].length
assert copied.empty?
ensure
@ -1048,7 +1048,7 @@ def test_skipping_migrations
skipped = []
on_skip = Proc.new { |name, migration| skipped << "#{name} #{migration.name}" }
copied = ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip)
copied = ActiveRecord::Migration.copy(@migrations_path, sources, on_skip: on_skip)
assert_equal 2, copied.length
assert_equal 1, skipped.length
@ -1066,8 +1066,8 @@ def test_skip_is_not_called_if_migrations_are_from_the_same_plugin
skipped = []
on_skip = Proc.new { |name, migration| skipped << "#{name} #{migration.name}" }
copied = ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip)
ActiveRecord::Migration.copy(@migrations_path, sources, :on_skip => on_skip)
copied = ActiveRecord::Migration.copy(@migrations_path, sources, on_skip: on_skip)
ActiveRecord::Migration.copy(@migrations_path, sources, on_skip: on_skip)
assert_equal 2, copied.length
assert_equal 0, skipped.length
@ -1080,7 +1080,7 @@ def test_copying_migrations_to_non_existing_directory
@existing_migrations = []
travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
assert File.exist?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb")
assert File.exist?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb")
assert_equal 2, copied.length
@ -1095,7 +1095,7 @@ def test_copying_migrations_to_empty_directory
@existing_migrations = []
travel_to(Time.utc(2010, 7, 26, 10, 10, 10)) do
copied = ActiveRecord::Migration.copy(@migrations_path, {:bukkits => MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
copied = ActiveRecord::Migration.copy(@migrations_path, {bukkits: MIGRATIONS_ROOT + "/to_copy_with_timestamps"})
assert File.exist?(@migrations_path + "/20100726101010_people_have_hobbies.bukkits.rb")
assert File.exist?(@migrations_path + "/20100726101011_people_have_descriptions.bukkits.rb")
assert_equal 2, copied.length

@ -115,7 +115,7 @@ def test_relative_migrations
end
def test_finds_pending_migrations
ActiveRecord::SchemaMigration.create!(:version => "1")
ActiveRecord::SchemaMigration.create!(version: "1")
migration_list = [ActiveRecord::Migration.new("foo", 1), ActiveRecord::Migration.new("bar", 3)]
migrations = ActiveRecord::Migrator.new(:up, migration_list).pending_migrations
@ -165,7 +165,7 @@ def test_down_calls_down
end
def test_current_version
ActiveRecord::SchemaMigration.create!(:version => "1000")
ActiveRecord::SchemaMigration.create!(version: "1000")
assert_equal 1000, ActiveRecord::Migrator.current_version
end
@ -332,7 +332,7 @@ def test_migrator_forward
def test_only_loads_pending_migrations
# migrate up to 1
ActiveRecord::SchemaMigration.create!(:version => "1")
ActiveRecord::SchemaMigration.create!(version: "1")
calls, migrator = migrator_class(3)
migrator.migrate("valid", nil)

@ -41,7 +41,7 @@ def test_module_spanning_has_and_belongs_to_many_associations
end
def test_associations_spanning_cross_modules
account = MyApplication::Billing::Account.all.merge!(: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
@ -50,7 +50,7 @@ def test_associations_spanning_cross_modules
end
def test_find_account_and_include_company
account = MyApplication::Billing::Account.all.merge!(:includes => :firm).find(1)
account = MyApplication::Billing::Account.all.merge!(includes: :firm).find(1)
assert_kind_of MyApplication::Business::Firm, account.firm
end
@ -73,8 +73,8 @@ def test_eager_loading_in_modules
clients = []
assert_nothing_raised do
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)
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|

Some files were not shown because too many files have changed in this diff Show More