applies new string literal convention in activerecord/test

The current code base is not uniform. After some discussion,
we have chosen to go with double quotes by default.
This commit is contained in:
Xavier Noria 2016-08-06 18:26:20 +02:00
parent 4df2b779dd
commit 9617db2078
280 changed files with 5678 additions and 5678 deletions

@ -100,31 +100,31 @@ def test_remove_index_when_name_and_wrong_column_name_specified
def test_current_database
if @connection.respond_to?(:current_database)
assert_equal ARTest.connection_config['arunit']['database'], @connection.current_database
assert_equal ARTest.connection_config["arunit"]["database"], @connection.current_database
end
end
if current_adapter?(:Mysql2Adapter)
def test_charset
assert_not_nil @connection.charset
assert_not_equal 'character_set_database', @connection.charset
assert_equal @connection.show_variable('character_set_database'), @connection.charset
assert_not_equal "character_set_database", @connection.charset
assert_equal @connection.show_variable("character_set_database"), @connection.charset
end
def test_collation
assert_not_nil @connection.collation
assert_not_equal 'collation_database', @connection.collation
assert_equal @connection.show_variable('collation_database'), @connection.collation
assert_not_equal "collation_database", @connection.collation
assert_equal @connection.show_variable("collation_database"), @connection.collation
end
def test_show_nonexistent_variable_returns_nil
assert_nil @connection.show_variable('foo_bar_baz')
assert_nil @connection.show_variable("foo_bar_baz")
end
def test_not_specifying_database_name_for_cross_database_selects
begin
assert_nothing_raised do
ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['arunit'].except(:database))
ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations["arunit"].except(:database))
config = ARTest.connection_config
ActiveRecord::Base.connection.execute(
@ -145,9 +145,9 @@ class << @connection
alias_method :table_alias_length, :test_table_alias_length
end
assert_equal 'posts', @connection.table_alias_for('posts')
assert_equal 'posts_comm', @connection.table_alias_for('posts_comments')
assert_equal 'dbo_posts', @connection.table_alias_for('dbo.posts')
assert_equal "posts", @connection.table_alias_for("posts")
assert_equal "posts_comm", @connection.table_alias_for("posts_comments")
assert_equal "dbo_posts", @connection.table_alias_for("dbo.posts")
class << @connection
remove_method :table_alias_length
@ -157,20 +157,20 @@ class << @connection
# test resetting sequences in odd tables in PostgreSQL
if ActiveRecord::Base.connection.respond_to?(:reset_pk_sequence!)
require 'models/movie'
require 'models/subscriber'
require "models/movie"
require "models/subscriber"
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
Movie.connection.reset_pk_sequence! "movies"
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.id = 'bob drake'
Subscriber.connection.reset_pk_sequence! "subscribers"
sub = Subscriber.new(:name => "robert drake")
sub.id = "bob drake"
assert_nothing_raised { sub.save! }
end
end
@ -201,7 +201,7 @@ def test_foreign_key_violations_are_translated_to_specific_exception
def test_foreign_key_violations_are_translated_to_specific_exception_with_validate_false
klass_has_fk = Class.new(ActiveRecord::Base) do
self.table_name = 'fk_test_has_fk'
self.table_name = "fk_test_has_fk"
end
error = assert_raises(ActiveRecord::InvalidForeignKey) do
@ -215,7 +215,7 @@ def test_foreign_key_violations_are_translated_to_specific_exception_with_valida
def test_value_limit_violations_are_translated_to_specific_exception
error = assert_raises(ActiveRecord::ValueTooLong) do
Event.create(title: 'abcdefgh')
Event.create(title: "abcdefgh")
end
assert_not_nil error.cause
@ -245,9 +245,9 @@ def test_select_all_always_return_activerecord_result
end
def test_select_methods_passing_a_association_relation
author = Author.create!(name: 'john')
Post.create!(author: author, title: 'foo', body: 'bar')
query = author.posts.where(title: 'foo').select(:title)
author = Author.create!(name: "john")
Post.create!(author: author, title: "foo", body: "bar")
query = author.posts.where(title: "foo").select(:title)
assert_equal({"title" => "foo"}, @connection.select_one(query.arel, nil, query.bound_attributes))
assert_equal({"title" => "foo"}, @connection.select_one(query))
assert @connection.select_all(query).is_a?(ActiveRecord::Result)
@ -256,8 +256,8 @@ def test_select_methods_passing_a_association_relation
end
def test_select_methods_passing_a_relation
Post.create!(title: 'foo', body: 'bar')
query = Post.where(title: 'foo').select(:title)
Post.create!(title: "foo", body: "bar")
query = Post.where(title: "foo").select(:title)
assert_equal({"title" => "foo"}, @connection.select_one(query.arel, nil, query.bound_attributes))
assert_equal({"title" => "foo"}, @connection.select_one(query))
assert @connection.select_all(query).is_a?(ActiveRecord::Result)
@ -273,7 +273,7 @@ def test_select_methods_passing_a_relation
def test_log_invalid_encoding
error = assert_raise ActiveRecord::StatementInvalid do
@connection.send :log, "SELECT 'ы' FROM DUAL" do
raise 'ы'.force_encoding(Encoding::ASCII_8BIT)
raise "ы".force_encoding(Encoding::ASCII_8BIT)
end
end

@ -1,5 +1,5 @@
require "cases/helper"
require 'support/connection_helper'
require "support/connection_helper"
class Mysql2ActiveSchemaTest < ActiveRecord::Mysql2TestCase
include ConnectionHelper
@ -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 `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
@ -120,7 +120,7 @@ def test_add_column_with_limit
end
def test_drop_table_with_specific_database
assert_equal "DROP TABLE `otherdb`.`people`", drop_table('otherdb.people')
assert_equal "DROP TABLE `otherdb`.`people`", drop_table("otherdb.people")
end
def test_add_timestamps
@ -128,8 +128,8 @@ def test_add_timestamps
begin
ActiveRecord::Base.connection.create_table :delete_me
ActiveRecord::Base.connection.add_timestamps :delete_me, null: true
assert column_present?('delete_me', 'updated_at', 'datetime')
assert column_present?('delete_me', 'created_at', 'datetime')
assert column_present?("delete_me", "updated_at", "datetime")
assert column_present?("delete_me", "created_at", "datetime")
ensure
ActiveRecord::Base.connection.drop_table :delete_me rescue nil
end
@ -143,8 +143,8 @@ def test_remove_timestamps
t.timestamps null: true
end
ActiveRecord::Base.connection.remove_timestamps :delete_me, { null: true }
assert !column_present?('delete_me', 'updated_at', 'datetime')
assert !column_present?('delete_me', 'created_at', 'datetime')
assert !column_present?("delete_me", "updated_at", "datetime")
assert !column_present?("delete_me", "created_at", "datetime")
ensure
ActiveRecord::Base.connection.drop_table :delete_me rescue nil
end
@ -185,6 +185,6 @@ def method_missing(method_symbol, *arguments)
def column_present?(table_name, column_name, type)
results = ActiveRecord::Base.connection.select_all("SHOW FIELDS FROM #{table_name} LIKE '#{column_name}'")
results.first && results.first['Type'] == type
results.first && results.first["Type"] == type
end
end

@ -1,5 +1,5 @@
require "cases/helper"
require 'models/topic'
require "models/topic"
module ActiveRecord
module ConnectionAdapters

@ -86,11 +86,11 @@ class BooleanType < ActiveRecord::Base
end
def boolean_column
BooleanType.columns.find { |c| c.name == 'archived' }
BooleanType.columns.find { |c| c.name == "archived" }
end
def string_column
BooleanType.columns.find { |c| c.name == 'published' }
BooleanType.columns.find { |c| c.name == "published" }
end
def emulate_booleans(value)

@ -7,19 +7,19 @@ class CollationTest < ActiveRecord::Base
repair_validations(CollationTest)
def test_columns_include_collation_different_from_table
assert_equal 'utf8_bin', CollationTest.columns_hash['string_cs_column'].collation
assert_equal 'utf8_general_ci', CollationTest.columns_hash['string_ci_column'].collation
assert_equal "utf8_bin", CollationTest.columns_hash["string_cs_column"].collation
assert_equal "utf8_general_ci", CollationTest.columns_hash["string_ci_column"].collation
end
def test_case_sensitive
assert !CollationTest.columns_hash['string_ci_column'].case_sensitive?
assert CollationTest.columns_hash['string_cs_column'].case_sensitive?
assert !CollationTest.columns_hash["string_ci_column"].case_sensitive?
assert CollationTest.columns_hash["string_cs_column"].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.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)
@ -27,8 +27,8 @@ def test_case_insensitive_comparison_for_ci_column
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.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)
@ -36,8 +36,8 @@ def test_case_insensitive_comparison_for_cs_column
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.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)
@ -45,8 +45,8 @@ def test_case_sensitive_comparison_for_ci_column
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.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)
@ -54,8 +54,8 @@ def test_case_sensitive_comparison_for_cs_column
def test_case_sensitive_comparison_for_binary_column
CollationTest.validates_uniqueness_of(:binary_column, case_sensitive: true)
CollationTest.create!(binary_column: 'A')
invalid = CollationTest.new(binary_column: 'A')
CollationTest.create!(binary_column: "A")
invalid = CollationTest.new(binary_column: "A")
queries = assert_sql { invalid.save }
bin_uniqueness_query = queries.detect { |q| q.match(/binary_column/) }
assert_no_match(/\bBINARY\b/, bin_uniqueness_query)

@ -1,5 +1,5 @@
require "cases/helper"
require 'support/schema_dumping_helper'
require "support/schema_dumping_helper"
class Mysql2CharsetCollationTest < ActiveRecord::Mysql2TestCase
include SchemaDumpingHelper
@ -8,8 +8,8 @@ class Mysql2CharsetCollationTest < ActiveRecord::Mysql2TestCase
setup do
@connection = ActiveRecord::Base.connection
@connection.create_table :charset_collations, force: true do |t|
t.string :string_ascii_bin, charset: 'ascii', collation: 'ascii_bin'
t.text :text_ucs2_unicode_ci, charset: 'ucs2', collation: 'ucs2_unicode_ci'
t.string :string_ascii_bin, charset: "ascii", collation: "ascii_bin"
t.text :text_ucs2_unicode_ci, charset: "ucs2", collation: "ucs2_unicode_ci"
end
end
@ -18,32 +18,32 @@ class Mysql2CharsetCollationTest < ActiveRecord::Mysql2TestCase
end
test "string column with charset and collation" do
column = @connection.columns(:charset_collations).find { |c| c.name == 'string_ascii_bin' }
column = @connection.columns(:charset_collations).find { |c| c.name == "string_ascii_bin" }
assert_equal :string, column.type
assert_equal 'ascii_bin', column.collation
assert_equal "ascii_bin", column.collation
end
test "text column with charset and collation" do
column = @connection.columns(:charset_collations).find { |c| c.name == 'text_ucs2_unicode_ci' }
column = @connection.columns(:charset_collations).find { |c| c.name == "text_ucs2_unicode_ci" }
assert_equal :text, column.type
assert_equal 'ucs2_unicode_ci', column.collation
assert_equal "ucs2_unicode_ci", column.collation
end
test "add column with charset and collation" do
@connection.add_column :charset_collations, :title, :string, charset: 'utf8', collation: 'utf8_bin'
@connection.add_column :charset_collations, :title, :string, charset: "utf8", collation: "utf8_bin"
column = @connection.columns(:charset_collations).find { |c| c.name == 'title' }
column = @connection.columns(:charset_collations).find { |c| c.name == "title" }
assert_equal :string, column.type
assert_equal 'utf8_bin', column.collation
assert_equal "utf8_bin", column.collation
end
test "change column with charset and collation" do
@connection.add_column :charset_collations, :description, :string, charset: 'utf8', collation: 'utf8_unicode_ci'
@connection.change_column :charset_collations, :description, :text, charset: 'utf8', collation: 'utf8_general_ci'
@connection.add_column :charset_collations, :description, :string, charset: "utf8", collation: "utf8_unicode_ci"
@connection.change_column :charset_collations, :description, :text, charset: "utf8", collation: "utf8_general_ci"
column = @connection.columns(:charset_collations).find { |c| c.name == 'description' }
column = @connection.columns(:charset_collations).find { |c| c.name == "description" }
assert_equal :text, column.type
assert_equal 'utf8_general_ci', column.collation
assert_equal "utf8_general_ci", column.collation
end
test "schema dump includes collation" do

@ -1,5 +1,5 @@
require "cases/helper"
require 'support/connection_helper'
require "support/connection_helper"
class Mysql2ConnectionTest < ActiveRecord::Mysql2TestCase
include ConnectionHelper
@ -9,7 +9,7 @@ class Mysql2ConnectionTest < ActiveRecord::Mysql2TestCase
def setup
super
@subscriber = SQLSubscriber.new
@subscription = ActiveSupport::Notifications.subscribe('sql.active_record', @subscriber)
@subscription = ActiveSupport::Notifications.subscribe("sql.active_record", @subscriber)
@connection = ActiveRecord::Base.connection
end
@ -20,9 +20,9 @@ def teardown
def test_bad_connection
assert_raise ActiveRecord::NoDatabaseError do
configuration = ActiveRecord::Base.configurations['arunit'].merge(database: 'inexistent_activerecord_unittest')
configuration = ActiveRecord::Base.configurations["arunit"].merge(database: "inexistent_activerecord_unittest")
connection = ActiveRecord::Base.mysql2_connection(configuration)
connection.drop_table 'ex', if_exists: true
connection.drop_table "ex", if_exists: true
end
end
@ -39,7 +39,7 @@ def test_truncate
def test_no_automatic_reconnection_after_timeout
assert @connection.active?
@connection.update('set @@wait_timeout=1')
@connection.update("set @@wait_timeout=1")
sleep 2
assert !@connection.active?
@ -49,7 +49,7 @@ def test_no_automatic_reconnection_after_timeout
def test_successful_reconnection_after_timeout_with_manual_reconnect
assert @connection.active?
@connection.update('set @@wait_timeout=1')
@connection.update("set @@wait_timeout=1")
sleep 2
@connection.reconnect!
assert @connection.active?
@ -57,15 +57,15 @@ def test_successful_reconnection_after_timeout_with_manual_reconnect
def test_successful_reconnection_after_timeout_with_verify
assert @connection.active?
@connection.update('set @@wait_timeout=1')
@connection.update("set @@wait_timeout=1")
sleep 2
@connection.verify!
assert @connection.active?
end
def test_mysql_connection_collation_is_configured
assert_equal 'utf8_unicode_ci', @connection.show_variable('collation_connection')
assert_equal 'utf8_general_ci', ARUnit2Model.connection.show_variable('collation_connection')
assert_equal "utf8_unicode_ci", @connection.show_variable("collation_connection")
assert_equal "utf8_general_ci", ARUnit2Model.connection.show_variable("collation_connection")
end
def test_mysql_default_in_strict_mode
@ -92,8 +92,8 @@ def test_mysql_strict_mode_specified_default
def test_mysql_sql_mode_variable_overrides_strict_mode
run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { 'sql_mode' => 'ansi' }))
result = ActiveRecord::Base.connection.select_value('SELECT @@SESSION.sql_mode')
ActiveRecord::Base.establish_connection(orig_connection.deep_merge(variables: { "sql_mode" => "ansi" }))
result = ActiveRecord::Base.connection.select_value("SELECT @@SESSION.sql_mode")
assert_no_match %r(STRICT_ALL_TABLES), result
end
end
@ -107,7 +107,7 @@ def test_passing_arbitary_flags_to_adapter
def test_passing_flags_by_array_to_adapter
run_without_connection do |orig_connection|
ActiveRecord::Base.establish_connection(orig_connection.merge({flags: ['COMPRESS'] }))
ActiveRecord::Base.establish_connection(orig_connection.merge({flags: ["COMPRESS"] }))
assert_equal ["COMPRESS", "FOUND_ROWS"], ActiveRecord::Base.connection.raw_connection.query_options[:flags]
end
end
@ -130,14 +130,14 @@ def test_mysql_set_session_variable_to_default
end
def test_logs_name_show_variable
@connection.show_variable 'foo'
@connection.show_variable "foo"
assert_equal "SCHEMA", @subscriber.logged[0][1]
end
def test_logs_name_rename_column_sql
@connection.execute "CREATE TABLE `bar_baz` (`foo` varchar(255))"
@subscriber.logged.clear
@connection.send(:rename_column_sql, 'bar_baz', 'foo', 'foo2')
@connection.send(:rename_column_sql, "bar_baz", "foo", "foo2")
assert_equal "SCHEMA", @subscriber.logged[0][1]
ensure
@connection.execute "DROP TABLE `bar_baz`"
@ -155,14 +155,14 @@ def test_get_and_release_advisory_lock
released_lock = @connection.release_advisory_lock(lock_name)
assert released_lock, "expected release_advisory_lock to return true but it didn't"
assert test_lock_free(lock_name), 'expected the test lock to be available after releasing'
assert test_lock_free(lock_name), "expected the test lock to be available after releasing"
end
def test_release_non_existent_advisory_lock
lock_name = "fake lock'n'name"
released_non_existent_lock = @connection.release_advisory_lock(lock_name)
assert_equal released_non_existent_lock, false,
'expected release_advisory_lock to return false when there was no lock to release'
"expected release_advisory_lock to return false when there was no lock to release"
end
protected

@ -5,23 +5,23 @@ class Mysql2DatetimePrecisionQuotingTest < ActiveRecord::Mysql2TestCase
@connection = ActiveRecord::Base.connection
end
test 'microsecond precision for MySQL gte 5.6.4' do
stub_version '5.6.4'
test "microsecond precision for MySQL gte 5.6.4" do
stub_version "5.6.4"
assert_microsecond_precision
end
test 'no microsecond precision for MySQL lt 5.6.4' do
stub_version '5.6.3'
test "no microsecond precision for MySQL lt 5.6.4" do
stub_version "5.6.3"
assert_no_microsecond_precision
end
test 'microsecond precision for MariaDB gte 5.3.0' do
stub_version '5.5.5-10.1.8-MariaDB-log'
test "microsecond precision for MariaDB gte 5.3.0" do
stub_version "5.5.5-10.1.8-MariaDB-log"
assert_microsecond_precision
end
test 'no microsecond precision for MariaDB lt 5.3.0' do
stub_version '5.2.9-MariaDB'
test "no microsecond precision for MariaDB lt 5.3.0" do
stub_version "5.2.9-MariaDB"
assert_no_microsecond_precision
end

@ -5,22 +5,22 @@ class EnumTest < ActiveRecord::Base
end
def test_enum_limit
column = EnumTest.columns_hash['enum_column']
column = EnumTest.columns_hash["enum_column"]
assert_equal 8, column.limit
end
def test_should_not_be_blob_or_text_column
column = EnumTest.columns_hash['enum_column']
column = EnumTest.columns_hash["enum_column"]
assert_not column.blob_or_text_column?
end
def test_should_not_be_unsigned
column = EnumTest.columns_hash['enum_column']
column = EnumTest.columns_hash["enum_column"]
assert_not column.unsigned?
end
def test_should_not_be_bigint
column = EnumTest.columns_hash['enum_column']
column = EnumTest.columns_hash["enum_column"]
assert_not column.bigint?
end
end

@ -1,6 +1,6 @@
require "cases/helper"
require 'models/developer'
require 'models/computer'
require "models/developer"
require "models/computer"
class Mysql2ExplainTest < ActiveRecord::Mysql2TestCase
fixtures :developers

@ -1,5 +1,5 @@
require 'cases/helper'
require 'support/schema_dumping_helper'
require "cases/helper"
require "support/schema_dumping_helper"
if ActiveRecord::Base.connection.supports_json?
class Mysql2JSONTest < ActiveRecord::Mysql2TestCase
@ -7,7 +7,7 @@ class Mysql2JSONTest < ActiveRecord::Mysql2TestCase
self.use_transactional_tests = false
class JsonDataType < ActiveRecord::Base
self.table_name = 'json_data_type'
self.table_name = "json_data_type"
store_accessor :settings, :resolution
end
@ -15,9 +15,9 @@ class JsonDataType < ActiveRecord::Base
def setup
@connection = ActiveRecord::Base.connection
begin
@connection.create_table('json_data_type') do |t|
t.json 'payload'
t.json 'settings'
@connection.create_table("json_data_type") do |t|
t.json "payload"
t.json "settings"
end
end
end
@ -30,18 +30,18 @@ def teardown
def test_column
column = JsonDataType.columns_hash["payload"]
assert_equal :json, column.type
assert_equal 'json', column.sql_type
assert_equal "json", column.sql_type
type = JsonDataType.type_for_attribute("payload")
assert_not type.binary?
end
def test_change_table_supports_json
@connection.change_table('json_data_type') do |t|
t.json 'users'
@connection.change_table("json_data_type") do |t|
t.json "users"
end
JsonDataType.reset_column_information
column = JsonDataType.columns_hash['users']
column = JsonDataType.columns_hash["users"]
assert_equal :json, column.type
end
@ -63,31 +63,31 @@ def test_type_cast_json
data = "{\"a_key\":\"a_value\"}"
hash = type.deserialize(data)
assert_equal({'a_key' => 'a_value'}, hash)
assert_equal({'a_key' => 'a_value'}, type.deserialize(data))
assert_equal({"a_key" => "a_value"}, hash)
assert_equal({"a_key" => "a_value"}, type.deserialize(data))
assert_equal({}, type.deserialize("{}"))
assert_equal({'key'=>nil}, type.deserialize('{"key": null}'))
assert_equal({'c'=>'}','"a"'=>'b "a b'}, type.deserialize(%q({"c":"}", "\"a\"":"b \"a b"})))
assert_equal({"key"=>nil}, type.deserialize('{"key": null}'))
assert_equal({"c"=>"}",'"a"'=>'b "a b'}, type.deserialize(%q({"c":"}", "\"a\"":"b \"a b"})))
end
def test_rewrite
@connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')"
x = JsonDataType.first
x.payload = { '"a\'' => 'b' }
x.payload = { '"a\'' => "b" }
assert x.save!
end
def test_select
@connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')"
x = JsonDataType.first
assert_equal({'k' => 'v'}, x.payload)
assert_equal({"k" => "v"}, x.payload)
end
def test_select_multikey
@connection.execute %q|insert into json_data_type (payload) VALUES ('{"k1":"v1", "k2":"v2", "k3":[1,2,3]}')|
x = JsonDataType.first
assert_equal({'k1' => 'v1', 'k2' => 'v2', 'k3' => [1,2,3]}, x.payload)
assert_equal({"k1" => "v1", "k2" => "v2", "k3" => [1,2,3]}, x.payload)
end
def test_null_json
@ -99,13 +99,13 @@ def test_null_json
def test_select_array_json_value
@connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')|
x = JsonDataType.first
assert_equal(['v0', {'k1' => 'v1'}], x.payload)
assert_equal(["v0", {"k1" => "v1"}], x.payload)
end
def test_rewrite_array_json_value
@connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')|
x = JsonDataType.first
x.payload = ['v1', {'k2' => 'v2'}, 'v3']
x.payload = ["v1", {"k2" => "v2"}, "v3"]
assert x.save!
end
@ -144,20 +144,20 @@ def test_changes_in_place
json = JsonDataType.new
assert_not json.changed?
json.payload = { 'one' => 'two' }
json.payload = { "one" => "two" }
assert json.changed?
assert json.payload_changed?
json.save!
assert_not json.changed?
json.payload['three'] = 'four'
json.payload["three"] = "four"
assert json.payload_changed?
json.save!
json.reload
assert_equal({ 'one' => 'two', 'three' => 'four' }, json.payload)
assert_equal({ "one" => "two", "three" => "four" }, json.payload)
assert_not json.changed?
end

@ -11,15 +11,15 @@ def setup
def test_exec_query_nothing_raises_with_no_result_queries
assert_nothing_raised do
with_example_table do
@conn.exec_query('INSERT INTO ex (number) VALUES (1)')
@conn.exec_query('DELETE FROM ex WHERE number = 1')
@conn.exec_query("INSERT INTO ex (number) VALUES (1)")
@conn.exec_query("DELETE FROM ex WHERE number = 1")
end
end
end
def test_valid_column
with_example_table do
column = @conn.columns('ex').find { |col| col.name == 'id' }
column = @conn.columns("ex").find { |col| col.name == "id" }
assert @conn.valid_type?(column.type)
end
end
@ -45,8 +45,8 @@ def test_columns_for_distinct_few_orders
def test_columns_for_distinct_with_case
assert_equal(
'posts.id, CASE WHEN author.is_active THEN UPPER(author.name) ELSE UPPER(author.email) END AS alias_0',
@conn.columns_for_distinct('posts.id',
"posts.id, CASE WHEN author.is_active THEN UPPER(author.name) ELSE UPPER(author.email) END AS alias_0",
@conn.columns_for_distinct("posts.id",
["CASE WHEN author.is_active THEN UPPER(author.name) ELSE UPPER(author.email) END"])
)
end
@ -67,7 +67,7 @@ def order.to_sql
private
def with_example_table(definition = 'id int auto_increment primary key, number int, data varchar(255)', &block)
super(@conn, 'ex', definition, &block)
def with_example_table(definition = "id int auto_increment primary key, number int, data varchar(255)", &block)
super(@conn, "ex", definition, &block)
end
end

@ -4,22 +4,22 @@
# reserved word names (ie: group, order, values, etc...)
class Mysql2ReservedWordTest < ActiveRecord::Mysql2TestCase
class Group < ActiveRecord::Base
Group.table_name = 'group'
Group.table_name = "group"
belongs_to :select
has_one :values
end
class Select < ActiveRecord::Base
Select.table_name = 'select'
Select.table_name = "select"
has_many :groups
end
class Values < ActiveRecord::Base
Values.table_name = 'values'
Values.table_name = "values"
end
class Distinct < ActiveRecord::Base
Distinct.table_name = 'distinct'
Distinct.table_name = "distinct"
has_and_belongs_to_many :selects
has_many :values, :through => :groups
end
@ -30,15 +30,15 @@ def setup
# we call execute directly here (and do similar below) because ActiveRecord::Base#create_table()
# will fail with these table names if these test cases fail
create_tables_directly 'group'=>'id int auto_increment primary key, `order` varchar(255), select_id int',
'select'=>'id int auto_increment primary key',
'values'=>'id int auto_increment primary key, group_id int',
'distinct'=>'id int auto_increment primary key',
'distinct_select'=>'distinct_id int, select_id int'
create_tables_directly "group"=>"id int auto_increment primary key, `order` varchar(255), select_id int",
"select"=>"id int auto_increment primary key",
"values"=>"id int auto_increment primary key, group_id int",
"distinct"=>"id int auto_increment primary key",
"distinct_select"=>"distinct_id int, select_id int"
end
teardown do
drop_tables_directly ['group', 'select', 'values', 'distinct', 'distinct_select', 'order']
drop_tables_directly ["group", "select", "values", "distinct", "distinct_select", "order"]
end
# create tables with reserved-word names and columns
@ -57,9 +57,9 @@ def test_rename_tables
# alter column with a reserved-word name in a table with a reserved-word name
def test_change_columns
assert_nothing_raised { @connection.change_column_default(:group, :order, 'whatever') }
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
@ -78,11 +78,11 @@ def test_activerecord_model
create_test_fixtures :select, :distinct, :group, :values, :distinct_select
x = nil
assert_nothing_raised { x = Group.new }
x.order = 'x'
x.order = "x"
assert_nothing_raised { x.save }
x.order = 'y'
x.order = "y"
assert_nothing_raised { x.save }
assert_nothing_raised { Group.find_by_order('y') }
assert_nothing_raised { Group.find_by_order("y") }
assert_nothing_raised { Group.find(1) }
end

@ -18,7 +18,7 @@ def test_initializes_schema_migrations_for_encoding_utf8mb4
connection.initialize_schema_migrations_table
assert connection.column_exists?(table_name, :version, :string, collation: 'utf8_general_ci')
assert connection.column_exists?(table_name, :version, :string, collation: "utf8_general_ci")
end
end
@ -29,7 +29,7 @@ def test_initializes_internal_metadata_for_encoding_utf8mb4
connection.initialize_internal_metadata_table
assert connection.column_exists?(table_name, :key, :string, collation: 'utf8_general_ci')
assert connection.column_exists?(table_name, :key, :string, collation: "utf8_general_ci")
end
end

@ -1,6 +1,6 @@
require "cases/helper"
require 'models/post'
require 'models/comment'
require "models/post"
require "models/comment"
module ActiveRecord
module ConnectionAdapters
@ -16,7 +16,7 @@ def setup
@omgpost = Class.new(ActiveRecord::Base) do
self.inheritance_column = :disabled
self.table_name = "#{db}.#{table}"
def self.name; 'Post'; end
def self.name; "Post"; end
end
end
@ -31,13 +31,13 @@ def test_float_limits
t.float :float_25, limit: 25
end
column_no_limit = @connection.columns(:mysql_doubles).find { |c| c.name == 'float_no_limit' }
column_short = @connection.columns(:mysql_doubles).find { |c| c.name == 'float_short' }
column_long = @connection.columns(:mysql_doubles).find { |c| c.name == 'float_long' }
column_no_limit = @connection.columns(:mysql_doubles).find { |c| c.name == "float_no_limit" }
column_short = @connection.columns(:mysql_doubles).find { |c| c.name == "float_short" }
column_long = @connection.columns(:mysql_doubles).find { |c| c.name == "float_long" }
column_23 = @connection.columns(:mysql_doubles).find { |c| c.name == 'float_23' }
column_24 = @connection.columns(:mysql_doubles).find { |c| c.name == 'float_24' }
column_25 = @connection.columns(:mysql_doubles).find { |c| c.name == 'float_25' }
column_23 = @connection.columns(:mysql_doubles).find { |c| c.name == "float_23" }
column_24 = @connection.columns(:mysql_doubles).find { |c| c.name == "float_24" }
column_25 = @connection.columns(:mysql_doubles).find { |c| c.name == "float_25" }
# Mysql floats are precision 0..24, Mysql doubles are precision 25..53
assert_equal 24, column_no_limit.limit
@ -56,7 +56,7 @@ def test_schema
end
def test_primary_key
assert_equal 'id', @omgpost.primary_key
assert_equal "id", @omgpost.primary_key
end
def test_data_source_exists?
@ -69,11 +69,11 @@ def test_data_source_exists_wrong_schema
end
def test_dump_indexes
index_a_name = 'index_key_tests_on_snack'
index_b_name = 'index_key_tests_on_pizza'
index_c_name = 'index_key_tests_on_awesome'
index_a_name = "index_key_tests_on_snack"
index_b_name = "index_key_tests_on_pizza"
index_c_name = "index_key_tests_on_awesome"
table = 'key_tests'
table = "key_tests"
indexes = @connection.indexes(table).sort_by(&:name)
assert_equal 3,indexes.size

@ -1,13 +1,13 @@
require "cases/helper"
require 'models/topic'
require 'models/reply'
require "models/topic"
require "models/reply"
class Mysql2StoredProcedureTest < ActiveRecord::Mysql2TestCase
fixtures :topics
def setup
@connection = ActiveRecord::Base.connection
unless ActiveRecord::Base.connection.version >= '5.6.0'
unless ActiveRecord::Base.connection.version >= "5.6.0"
skip("no stored procedure support")
end
end
@ -17,19 +17,19 @@ def setup
# In MySQL 5.6, CLIENT_MULTI_RESULTS is enabled by default.
# http://dev.mysql.com/doc/refman/5.6/en/call.html
def test_multi_results
rows = @connection.select_rows('CALL ten();')
rows = @connection.select_rows("CALL ten();")
assert_equal 10, rows[0][0].to_i, "ten() did not return 10 as expected: #{rows.inspect}"
assert @connection.active?, "Bad connection use by 'Mysql2Adapter.select_rows'"
end
def test_multi_results_from_select_one
row = @connection.select_one('CALL topics(1);')
assert_equal 'David', row['author_name']
row = @connection.select_one("CALL topics(1);")
assert_equal "David", row["author_name"]
assert @connection.active?, "Bad connection use by 'Mysql2Adapter.select_one'"
end
def test_multi_results_from_find_by_sql
topics = Topic.find_by_sql 'CALL topics(3);'
topics = Topic.find_by_sql "CALL topics(3);"
assert_equal 3, topics.size
assert @connection.active?, "Bad connection use by 'Mysql2Adapter.select'"
end

@ -2,10 +2,10 @@
class Mysql2SqlTypesTest < ActiveRecord::Mysql2TestCase
def test_binary_types
assert_equal 'varbinary(64)', type_to_sql(:binary, 64)
assert_equal 'varbinary(4095)', type_to_sql(:binary, 4095)
assert_equal 'blob', type_to_sql(:binary, 4096)
assert_equal 'blob', type_to_sql(:binary)
assert_equal "varbinary(64)", type_to_sql(:binary, 64)
assert_equal "varbinary(4095)", type_to_sql(:binary, 4095)
assert_equal "blob", type_to_sql(:binary, 4096)
assert_equal "blob", type_to_sql(:binary)
end
def type_to_sql(*args)

@ -1,5 +1,5 @@
require "cases/helper"
require 'support/schema_dumping_helper'
require "support/schema_dumping_helper"
class Mysql2TableOptionsTest < ActiveRecord::Mysql2TestCase
include SchemaDumpingHelper

@ -1,12 +1,12 @@
require "cases/helper"
require 'support/connection_helper'
require "support/connection_helper"
module ActiveRecord
class Mysql2TransactionTest < ActiveRecord::Mysql2TestCase
self.use_transactional_tests = false
class Sample < ActiveRecord::Base
self.table_name = 'samples'
self.table_name = "samples"
end
setup do
@ -14,9 +14,9 @@ class Sample < ActiveRecord::Base
@connection.clear_cache!
@connection.transaction do
@connection.drop_table 'samples', if_exists: true
@connection.create_table('samples') do |t|
t.integer 'value'
@connection.drop_table "samples", if_exists: true
@connection.create_table("samples") do |t|
t.integer "value"
end
end
@ -24,7 +24,7 @@ class Sample < ActiveRecord::Base
end
teardown do
@connection.drop_table 'samples', if_exists: true
@connection.drop_table "samples", if_exists: true
end
test "raises Deadlocked when a deadlock is encountered" do

@ -1,4 +1,4 @@
require 'cases/helper'
require "cases/helper"
class PostgresqlActiveSchemaTest < ActiveRecord::PostgreSQLTestCase
def setup
@ -16,7 +16,7 @@ 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
@ -31,10 +31,10 @@ def test_add_index
assert_equal expected, add_index(:people, :last_name, unique: true, where: "state = 'active'")
expected = %(CREATE UNIQUE INDEX "index_people_on_lower_last_name" ON "people" (lower(last_name)))
assert_equal expected, add_index(:people, 'lower(last_name)', unique: true)
assert_equal expected, add_index(:people, "lower(last_name)", unique: true)
expected = %(CREATE UNIQUE INDEX "index_people_on_last_name_varchar_pattern_ops" ON "people" (last_name varchar_pattern_ops))
assert_equal expected, add_index(:people, 'last_name varchar_pattern_ops', unique: true)
assert_equal expected, add_index(:people, "last_name varchar_pattern_ops", unique: true)
expected = %(CREATE INDEX CONCURRENTLY "index_people_on_last_name" ON "people" ("last_name"))
assert_equal expected, add_index(:people, :last_name, algorithm: :concurrently)
@ -50,7 +50,7 @@ def test_add_index
assert_equal expected, add_index(:people, :last_name, using: type, unique: true, where: "state = 'active'")
expected = %(CREATE UNIQUE INDEX "index_people_on_lower_last_name" ON "people" USING #{type} (lower(last_name)))
assert_equal expected, add_index(:people, 'lower(last_name)', using: type, unique: true)
assert_equal expected, add_index(:people, "lower(last_name)", using: type, unique: true)
end
assert_raise ArgumentError do
@ -63,7 +63,7 @@ def test_add_index
def test_remove_index
# remove_index calls index_name_for_remove which can't work since execute is stubbed
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.send(:define_method, :index_name_for_remove) do |*|
'index_people_on_last_name'
"index_people_on_last_name"
end
expected = %(DROP INDEX CONCURRENTLY "index_people_on_last_name")

@ -1,35 +1,35 @@
require "cases/helper"
require 'support/schema_dumping_helper'
require "support/schema_dumping_helper"
class PostgresqlArrayTest < ActiveRecord::PostgreSQLTestCase
include SchemaDumpingHelper
include InTimeZone
class PgArray < ActiveRecord::Base
self.table_name = 'pg_arrays'
self.table_name = "pg_arrays"
end
def setup
@connection = ActiveRecord::Base.connection
enable_extension!('hstore', @connection)
enable_extension!("hstore", @connection)
@connection.transaction do
@connection.create_table('pg_arrays') do |t|
t.string 'tags', array: true
t.integer 'ratings', array: true
@connection.create_table("pg_arrays") do |t|
t.string "tags", array: true
t.integer "ratings", array: true
t.datetime :datetimes, array: true
t.hstore :hstores, array: true
end
end
PgArray.reset_column_information
@column = PgArray.columns_hash['tags']
@column = PgArray.columns_hash["tags"]
@type = PgArray.type_for_attribute("tags")
end
teardown do
@connection.drop_table 'pg_arrays', if_exists: true
disable_extension!('hstore', @connection)
@connection.drop_table "pg_arrays", if_exists: true
disable_extension!("hstore", @connection)
end
def test_column
@ -38,26 +38,26 @@ def test_column
assert @column.array?
assert_not @type.binary?
ratings_column = PgArray.columns_hash['ratings']
ratings_column = PgArray.columns_hash["ratings"]
assert_equal :integer, ratings_column.type
assert ratings_column.array?
end
def test_default
@connection.add_column 'pg_arrays', 'score', :integer, array: true, default: [4, 4, 2]
@connection.add_column "pg_arrays", "score", :integer, array: true, default: [4, 4, 2]
PgArray.reset_column_information
assert_equal([4, 4, 2], PgArray.column_defaults['score'])
assert_equal([4, 4, 2], PgArray.column_defaults["score"])
assert_equal([4, 4, 2], PgArray.new.score)
ensure
PgArray.reset_column_information
end
def test_default_strings
@connection.add_column 'pg_arrays', 'names', :string, array: true, default: ["foo", "bar"]
@connection.add_column "pg_arrays", "names", :string, array: true, default: ["foo", "bar"]
PgArray.reset_column_information
assert_equal(["foo", "bar"], PgArray.column_defaults['names'])
assert_equal(["foo", "bar"], PgArray.column_defaults["names"])
assert_equal(["foo", "bar"], PgArray.new.names)
ensure
PgArray.reset_column_information
@ -68,10 +68,10 @@ def test_change_column_with_array
@connection.change_column :pg_arrays, :snippets, :text, array: true, default: []
PgArray.reset_column_information
column = PgArray.columns_hash['snippets']
column = PgArray.columns_hash["snippets"]
assert_equal :text, column.type
assert_equal [], PgArray.column_defaults['snippets']
assert_equal [], PgArray.column_defaults["snippets"]
assert column.array?
end
@ -88,17 +88,17 @@ def test_change_column_default_with_array
@connection.change_column_default :pg_arrays, :tags, []
PgArray.reset_column_information
assert_equal [], PgArray.column_defaults['tags']
assert_equal [], PgArray.column_defaults["tags"]
end
def test_type_cast_array
assert_equal(['1', '2', '3'], @type.deserialize('{1,2,3}'))
assert_equal([], @type.deserialize('{}'))
assert_equal([nil], @type.deserialize('{NULL}'))
assert_equal(["1", "2", "3"], @type.deserialize("{1,2,3}"))
assert_equal([], @type.deserialize("{}"))
assert_equal([nil], @type.deserialize("{NULL}"))
end
def test_type_cast_integers
x = PgArray.new(ratings: ['1', '2'])
x = PgArray.new(ratings: ["1", "2"])
assert_equal([1, 2], x.ratings)
@ -117,15 +117,15 @@ def test_schema_dump_with_shorthand
def test_select_with_strings
@connection.execute "insert into pg_arrays (tags) VALUES ('{1,2,3}')"
x = PgArray.first
assert_equal(['1','2','3'], x.tags)
assert_equal(["1","2","3"], x.tags)
end
def test_rewrite_with_strings
@connection.execute "insert into pg_arrays (tags) VALUES ('{1,2,3}')"
x = PgArray.first
x.tags = ['1','2','3','4']
x.tags = ["1","2","3","4"]
x.save!
assert_equal ['1','2','3','4'], x.reload.tags
assert_equal ["1","2","3","4"], x.reload.tags
end
def test_select_with_integers
@ -137,25 +137,25 @@ def test_select_with_integers
def test_rewrite_with_integers
@connection.execute "insert into pg_arrays (ratings) VALUES ('{1,2,3}')"
x = PgArray.first
x.ratings = [2, '3', 4]
x.ratings = [2, "3", 4]
x.save!
assert_equal [2, 3, 4], x.reload.ratings
end
def test_multi_dimensional_with_strings
assert_cycle(:tags, [[['1'], ['2']], [['2'], ['3']]])
assert_cycle(:tags, [[["1"], ["2"]], [["2"], ["3"]]])
end
def test_with_empty_strings
assert_cycle(:tags, [ '1', '2', '', '4', '', '5' ])
assert_cycle(:tags, [ "1", "2", "", "4", "", "5" ])
end
def test_with_multi_dimensional_empty_strings
assert_cycle(:tags, [[['1', '2'], ['', '4'], ['', '5']]])
assert_cycle(:tags, [[["1", "2"], ["", "4"], ["", "5"]]])
end
def test_with_arbitrary_whitespace
assert_cycle(:tags, [[['1', '2'], [' ', '4'], [' ', '5']]])
assert_cycle(:tags, [[["1", "2"], [" ", "4"], [" ", "5"]]])
end
def test_multi_dimensional_with_integers
@ -163,23 +163,23 @@ def test_multi_dimensional_with_integers
end
def test_strings_with_quotes
assert_cycle(:tags, ['this has','some "s that need to be escaped"'])
assert_cycle(:tags, ["this has",'some "s that need to be escaped"'])
end
def test_strings_with_commas
assert_cycle(:tags, ['this,has','many,values'])
assert_cycle(:tags, ["this,has","many,values"])
end
def test_strings_with_array_delimiters
assert_cycle(:tags, ['{','}'])
assert_cycle(:tags, ["{","}"])
end
def test_strings_with_null_strings
assert_cycle(:tags, ['NULL','NULL'])
assert_cycle(:tags, ["NULL","NULL"])
end
def test_contains_nils
assert_cycle(:tags, ['1',nil,nil])
assert_cycle(:tags, ["1",nil,nil])
end
def test_insert_fixture
@ -211,14 +211,14 @@ def test_string_quoting_rules_match_pg_behavior
x = PgArray.create!(tags: tags)
x.reload
assert_equal x.tags_before_type_cast, PgArray.type_for_attribute('tags').serialize(tags)
assert_equal x.tags_before_type_cast, PgArray.type_for_attribute("tags").serialize(tags)
end
def test_quoting_non_standard_delimiters
strings = ["hello,", "world;"]
oid = ActiveRecord::ConnectionAdapters::PostgreSQL::OID
comma_delim = oid::Array.new(ActiveRecord::Type::String.new, ',')
semicolon_delim = oid::Array.new(ActiveRecord::Type::String.new, ';')
comma_delim = oid::Array.new(ActiveRecord::Type::String.new, ",")
semicolon_delim = oid::Array.new(ActiveRecord::Type::String.new, ";")
assert_equal %({"hello,",world;}), comma_delim.serialize(strings)
assert_equal %({hello,;"world;"}), semicolon_delim.serialize(strings)
@ -236,13 +236,13 @@ def test_mutate_array
end
def test_mutate_value_in_array
x = PgArray.create!(hstores: [{ a: 'a' }, { b: 'b' }])
x = PgArray.create!(hstores: [{ a: "a" }, { b: "b" }])
x.hstores.first['a'] = 'c'
x.hstores.first["a"] = "c"
x.save!
x.reload
assert_equal [{ 'a' => 'c' }, { 'b' => 'b' }], x.hstores
assert_equal [{ "a" => "c" }, { "b" => "b" }], x.hstores
assert_not x.changed?
end

@ -1,6 +1,6 @@
require "cases/helper"
require 'support/connection_helper'
require 'support/schema_dumping_helper'
require "support/connection_helper"
require "support/schema_dumping_helper"
class PostgresqlBitStringTest < ActiveRecord::PostgreSQLTestCase
include ConnectionHelper
@ -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
@ -20,7 +20,7 @@ def setup
def teardown
return unless @connection
@connection.drop_table 'postgresql_bit_strings', if_exists: true
@connection.drop_table "postgresql_bit_strings", if_exists: true
end
def test_bit_string_column
@ -44,10 +44,10 @@ def test_bit_string_varying_column
end
def test_default
assert_equal "00000011", PostgresqlBitString.column_defaults['a_bit']
assert_equal "00000011", PostgresqlBitString.column_defaults["a_bit"]
assert_equal "00000011", PostgresqlBitString.new.a_bit
assert_equal "0011", PostgresqlBitString.column_defaults['a_bit_varying']
assert_equal "0011", PostgresqlBitString.column_defaults["a_bit_varying"]
assert_equal "0011", PostgresqlBitString.new.a_bit_varying
end

@ -1,29 +1,29 @@
require "cases/helper"
require 'support/schema_dumping_helper'
require "support/schema_dumping_helper"
class PostgresqlByteaTest < ActiveRecord::PostgreSQLTestCase
include SchemaDumpingHelper
class ByteaDataType < ActiveRecord::Base
self.table_name = 'bytea_data_type'
self.table_name = "bytea_data_type"
end
def setup
@connection = ActiveRecord::Base.connection
begin
@connection.transaction do
@connection.create_table('bytea_data_type') do |t|
t.binary 'payload'
t.binary 'serialized'
@connection.create_table("bytea_data_type") do |t|
t.binary "payload"
t.binary "serialized"
end
end
end
@column = ByteaDataType.columns_hash['payload']
@column = ByteaDataType.columns_hash["payload"]
@type = ByteaDataType.type_for_attribute("payload")
end
teardown do
@connection.drop_table 'bytea_data_type', if_exists: true
@connection.drop_table "bytea_data_type", if_exists: true
end
def test_column
@ -32,7 +32,7 @@ def test_column
end
def test_binary_columns_are_limitless_the_upper_limit_is_one_GB
assert_equal 'bytea', @connection.type_to_sql(:binary, 100_000)
assert_equal "bytea", @connection.type_to_sql(:binary, 100_000)
assert_raise ActiveRecord::ActiveRecordError do
@connection.type_to_sql :binary, 4294967295
end
@ -42,8 +42,8 @@ def test_type_cast_binary_converts_the_encoding
assert @column
data = "\u001F\x8B"
assert_equal('UTF-8', data.encoding.name)
assert_equal('ASCII-8BIT', @type.deserialize(data).encoding.name)
assert_equal("UTF-8", data.encoding.name)
assert_equal("ASCII-8BIT", @type.deserialize(data).encoding.name)
end
def test_type_cast_binary_value
@ -88,14 +88,14 @@ def test_via_to_sql
def test_via_to_sql_with_complicating_connection
Thread.new do
other_conn = ActiveRecord::Base.connection
other_conn.execute('SET standard_conforming_strings = off')
other_conn.execute("SET standard_conforming_strings = off")
end.join
test_via_to_sql
end
def test_write_binary
data = File.read(File.join(File.dirname(__FILE__), '..', '..', '..', 'assets', 'example.log'))
data = File.read(File.join(File.dirname(__FILE__), "..", "..", "..", "assets", "example.log"))
assert(data.size > 1)
record = ByteaDataType.create(payload: data)
assert_not record.new_record?

@ -1,4 +1,4 @@
require 'cases/helper'
require "cases/helper"
module ActiveRecord
class Migration
@ -19,17 +19,17 @@ def teardown
def test_change_string_to_date
connection.change_column :strings, :somedate, :timestamp, using: 'CAST("somedate" AS timestamp)'
assert_equal :datetime, connection.columns(:strings).find { |c| c.name == 'somedate' }.type
assert_equal :datetime, connection.columns(:strings).find { |c| c.name == "somedate" }.type
end
def test_change_type_with_symbol
connection.change_column :strings, :somedate, :timestamp, cast_as: :timestamp
assert_equal :datetime, connection.columns(:strings).find { |c| c.name == 'somedate' }.type
assert_equal :datetime, connection.columns(:strings).find { |c| c.name == "somedate" }.type
end
def test_change_type_with_array
connection.change_column :strings, :somedate, :timestamp, array: true, cast_as: :timestamp
column = connection.columns(:strings).find { |c| c.name == 'somedate' }
column = connection.columns(:strings).find { |c| c.name == "somedate" }
assert_equal :datetime, column.type
assert column.array?
end

@ -1,49 +1,49 @@
require 'cases/helper'
require 'support/schema_dumping_helper'
require "cases/helper"
require "support/schema_dumping_helper"
if ActiveRecord::Base.connection.supports_extensions?
class PostgresqlCitextTest < ActiveRecord::PostgreSQLTestCase
include SchemaDumpingHelper
class Citext < ActiveRecord::Base
self.table_name = 'citexts'
self.table_name = "citexts"
end
def setup
@connection = ActiveRecord::Base.connection
enable_extension!('citext', @connection)
enable_extension!("citext", @connection)
@connection.create_table('citexts') do |t|
t.citext 'cival'
@connection.create_table("citexts") do |t|
t.citext "cival"
end
end
teardown do
@connection.drop_table 'citexts', if_exists: true
disable_extension!('citext', @connection)
@connection.drop_table "citexts", if_exists: true
disable_extension!("citext", @connection)
end
def test_citext_enabled
assert @connection.extension_enabled?('citext')
assert @connection.extension_enabled?("citext")
end
def test_column
column = Citext.columns_hash['cival']
column = Citext.columns_hash["cival"]
assert_equal :citext, column.type
assert_equal 'citext', column.sql_type
assert_equal "citext", column.sql_type
assert_not column.array?
type = Citext.type_for_attribute('cival')
type = Citext.type_for_attribute("cival")
assert_not type.binary?
end
def test_change_table_supports_json
@connection.transaction do
@connection.change_table('citexts') do |t|
t.citext 'username'
@connection.change_table("citexts") do |t|
t.citext "username"
end
Citext.reset_column_information
column = Citext.columns_hash['username']
column = Citext.columns_hash["username"]
assert_equal :citext, column.type
raise ActiveRecord::Rollback # reset the schema change
@ -53,7 +53,7 @@ def test_change_table_supports_json
end
def test_write
x = Citext.new(cival: 'Some CI Text')
x = Citext.new(cival: "Some CI Text")
x.save!
citext = Citext.first
assert_equal "Some CI Text", citext.cival
@ -66,8 +66,8 @@ def test_write
def test_select_case_insensitive
@connection.execute "insert into citexts (cival) values('Cased Text')"
x = Citext.where(cival: 'cased text').first
assert_equal 'Cased Text', x.cival
x = Citext.where(cival: "cased text").first
assert_equal "Cased Text", x.cival
end
def test_schema_dump_with_shorthand

@ -1,5 +1,5 @@
require "cases/helper"
require 'support/schema_dumping_helper'
require "support/schema_dumping_helper"
class PostgresqlCollationTest < ActiveRecord::PostgreSQLTestCase
include SchemaDumpingHelper
@ -7,8 +7,8 @@ class PostgresqlCollationTest < ActiveRecord::PostgreSQLTestCase
def setup
@connection = ActiveRecord::Base.connection
@connection.create_table :postgresql_collations, force: true do |t|
t.string :string_c, collation: 'C'
t.text :text_posix, collation: 'POSIX'
t.string :string_c, collation: "C"
t.text :text_posix, collation: "POSIX"
end
end
@ -17,32 +17,32 @@ def teardown
end
test "string column with collation" do
column = @connection.columns(:postgresql_collations).find { |c| c.name == 'string_c' }
column = @connection.columns(:postgresql_collations).find { |c| c.name == "string_c" }
assert_equal :string, column.type
assert_equal 'C', column.collation
assert_equal "C", column.collation
end
test "text column with collation" do
column = @connection.columns(:postgresql_collations).find { |c| c.name == 'text_posix' }
column = @connection.columns(:postgresql_collations).find { |c| c.name == "text_posix" }
assert_equal :text, column.type
assert_equal 'POSIX', column.collation
assert_equal "POSIX", column.collation
end
test "add column with collation" do
@connection.add_column :postgresql_collations, :title, :string, collation: 'C'
@connection.add_column :postgresql_collations, :title, :string, collation: "C"
column = @connection.columns(:postgresql_collations).find { |c| c.name == 'title' }
column = @connection.columns(:postgresql_collations).find { |c| c.name == "title" }
assert_equal :string, column.type
assert_equal 'C', column.collation
assert_equal "C", column.collation
end
test "change column with collation" do
@connection.add_column :postgresql_collations, :description, :string
@connection.change_column :postgresql_collations, :description, :text, collation: 'POSIX'
@connection.change_column :postgresql_collations, :description, :text, collation: "POSIX"
column = @connection.columns(:postgresql_collations).find { |c| c.name == 'description' }
column = @connection.columns(:postgresql_collations).find { |c| c.name == "description" }
assert_equal :text, column.type
assert_equal 'POSIX', column.collation
assert_equal "POSIX", column.collation
end
test "schema dump includes collation" do

@ -1,5 +1,5 @@
require "cases/helper"
require 'support/connection_helper'
require "support/connection_helper"
module PostgresqlCompositeBehavior
include ConnectionHelper
@ -20,7 +20,7 @@ def setup
street VARCHAR(90)
);
SQL
@connection.create_table('postgresql_composites') do |t|
@connection.create_table("postgresql_composites") do |t|
t.column :address, :full_address
end
end
@ -29,8 +29,8 @@ def setup
def teardown
super
@connection.drop_table 'postgresql_composites', if_exists: true
@connection.execute 'DROP TYPE IF EXISTS full_address'
@connection.drop_table "postgresql_composites", if_exists: true
@connection.execute "DROP TYPE IF EXISTS full_address"
reset_connection
PostgresqlComposite.reset_column_information
end
@ -126,7 +126,7 @@ def test_composite_mapping
composite.address = FullAddress.new("Paris", "Rue Basse")
composite.save!
assert_equal 'Paris', composite.reload.address.city
assert_equal 'Rue Basse', composite.reload.address.street
assert_equal "Paris", composite.reload.address.city
assert_equal "Rue Basse", composite.reload.address.street
end
end

@ -1,5 +1,5 @@
require "cases/helper"
require 'support/connection_helper'
require "support/connection_helper"
module ActiveRecord
class PostgresqlConnectionTest < ActiveRecord::PostgreSQLTestCase
@ -13,7 +13,7 @@ class NonExistentTable < ActiveRecord::Base
def setup
super
@subscriber = SQLSubscriber.new
@subscription = ActiveSupport::Notifications.subscribe('sql.active_record', @subscriber)
@subscription = ActiveSupport::Notifications.subscribe("sql.active_record", @subscriber)
@connection = ActiveRecord::Base.connection
end
@ -23,10 +23,10 @@ def teardown
end
def test_truncate
count = ActiveRecord::Base.connection.execute("select count(*) from comments").first['count'].to_i
count = ActiveRecord::Base.connection.execute("select count(*) from comments").first["count"].to_i
assert_operator count, :>, 0
ActiveRecord::Base.connection.truncate("comments")
count = ActiveRecord::Base.connection.execute("select count(*) from comments").first['count'].to_i
count = ActiveRecord::Base.connection.execute("select count(*) from comments").first["count"].to_i
assert_equal 0, count
end
@ -54,85 +54,85 @@ def test_connection_options
NonExistentTable.establish_connection(params)
# Verify the connection param has been applied.
expect = NonExistentTable.connection.query('show geqo').first.first
assert_equal 'off', expect
expect = NonExistentTable.connection.query("show geqo").first.first
assert_equal "off", expect
end
def test_reset
@connection.query('ROLLBACK')
@connection.query('SET geqo TO off')
@connection.query("ROLLBACK")
@connection.query("SET geqo TO off")
# Verify the setting has been applied.
expect = @connection.query('show geqo').first.first
assert_equal 'off', expect
expect = @connection.query("show geqo").first.first
assert_equal "off", expect
@connection.reset!
# Verify the setting has been cleared.
expect = @connection.query('show geqo').first.first
assert_equal 'on', expect
expect = @connection.query("show geqo").first.first
assert_equal "on", expect
end
def test_reset_with_transaction
@connection.query('ROLLBACK')
@connection.query('SET geqo TO off')
@connection.query("ROLLBACK")
@connection.query("SET geqo TO off")
# Verify the setting has been applied.
expect = @connection.query('show geqo').first.first
assert_equal 'off', expect
expect = @connection.query("show geqo").first.first
assert_equal "off", expect
@connection.query('BEGIN')
@connection.query("BEGIN")
@connection.reset!
# Verify the setting has been cleared.
expect = @connection.query('show geqo').first.first
assert_equal 'on', expect
expect = @connection.query("show geqo").first.first
assert_equal "on", expect
end
def test_tables_logs_name
ActiveSupport::Deprecation.silence { @connection.tables('hello') }
assert_equal 'SCHEMA', @subscriber.logged[0][1]
ActiveSupport::Deprecation.silence { @connection.tables("hello") }
assert_equal "SCHEMA", @subscriber.logged[0][1]
end
def test_indexes_logs_name
@connection.indexes('items', 'hello')
assert_equal 'SCHEMA', @subscriber.logged[0][1]
@connection.indexes("items", "hello")
assert_equal "SCHEMA", @subscriber.logged[0][1]
end
def test_table_exists_logs_name
ActiveSupport::Deprecation.silence { @connection.table_exists?('items') }
assert_equal 'SCHEMA', @subscriber.logged[0][1]
ActiveSupport::Deprecation.silence { @connection.table_exists?("items") }
assert_equal "SCHEMA", @subscriber.logged[0][1]
end
def test_table_alias_length_logs_name
@connection.instance_variable_set("@table_alias_length", nil)
@connection.table_alias_length
assert_equal 'SCHEMA', @subscriber.logged[0][1]
assert_equal "SCHEMA", @subscriber.logged[0][1]
end
def test_current_database_logs_name
@connection.current_database
assert_equal 'SCHEMA', @subscriber.logged[0][1]
assert_equal "SCHEMA", @subscriber.logged[0][1]
end
def test_encoding_logs_name
@connection.encoding
assert_equal 'SCHEMA', @subscriber.logged[0][1]
assert_equal "SCHEMA", @subscriber.logged[0][1]
end
def test_schema_names_logs_name
@connection.schema_names
assert_equal 'SCHEMA', @subscriber.logged[0][1]
assert_equal "SCHEMA", @subscriber.logged[0][1]
end
if ActiveRecord::Base.connection.prepared_statements
def test_statement_key_is_logged
bind = Relation::QueryAttribute.new(nil, 1, Type::Value.new)
@connection.exec_query('SELECT $1::integer', 'SQL', [bind], prepare: true)
@connection.exec_query("SELECT $1::integer", "SQL", [bind], prepare: true)
name = @subscriber.payloads.last[:statement_name]
assert name
res = @connection.exec_query("EXPLAIN (FORMAT JSON) EXECUTE #{name}(1)")
plan = res.column_types['QUERY PLAN'].deserialize res.rows.first.first
plan = res.column_types["QUERY PLAN"].deserialize res.rows.first.first
assert_operator plan.length, :>, 0
end
end
@ -146,7 +146,7 @@ def test_statement_key_is_logged
# To restart PostgreSQL 9.1 on OS X, installed via MacPorts, ...
# sudo su postgres -c "pg_ctl restart -D /opt/local/var/db/postgresql91/defaultdb/ -m fast"
def test_reconnection_after_actual_disconnection_with_verify
original_connection_pid = @connection.query('select pg_backend_pid()')
original_connection_pid = @connection.query("select pg_backend_pid()")
# Sanity check.
assert @connection.active?
@ -155,8 +155,8 @@ def test_reconnection_after_actual_disconnection_with_verify
secondary_connection = ActiveRecord::Base.connection_pool.checkout
secondary_connection.query("select pg_terminate_backend(#{original_connection_pid.first.first})")
ActiveRecord::Base.connection_pool.checkin(secondary_connection)
elsif ARTest.config['with_manual_interventions']
puts 'Kill the connection now (e.g. by restarting the PostgreSQL ' +
elsif ARTest.config["with_manual_interventions"]
puts "Kill the connection now (e.g. by restarting the PostgreSQL " +
'server with the "-m fast" option) and then press enter.'
$stdin.gets
else
@ -172,7 +172,7 @@ def test_reconnection_after_actual_disconnection_with_verify
# If we get no exception here, then either we re-connected successfully, or
# we never actually got disconnected.
new_connection_pid = @connection.query('select pg_backend_pid()')
new_connection_pid = @connection.query("select pg_backend_pid()")
assert_not_equal original_connection_pid, new_connection_pid,
"umm -- looks like you didn't break the connection, because we're still " +
@ -241,7 +241,7 @@ def test_release_non_existent_advisory_lock
with_warning_suppression do
released_non_existent_lock = @connection.release_advisory_lock(fake_lock_id)
assert_equal released_non_existent_lock, false,
'expected release_advisory_lock to return false when there was no lock to release'
"expected release_advisory_lock to return false when there was no lock to release"
end
end
@ -249,7 +249,7 @@ def test_release_non_existent_advisory_lock
def with_warning_suppression
log_level = @connection.client_min_messages
@connection.client_min_messages = 'error'
@connection.client_min_messages = "error"
yield
@connection.client_min_messages = log_level
end

@ -1,5 +1,5 @@
require "cases/helper"
require 'support/ddl_helper'
require "support/ddl_helper"
class PostgresqlTime < ActiveRecord::Base
@ -38,8 +38,8 @@ def test_data_type_of_oid_types
end
def test_time_values
assert_equal '-1 years -2 days', @first_time.time_interval
assert_equal '-21 days', @first_time.scaled_time_interval
assert_equal "-1 years -2 days", @first_time.time_interval
assert_equal "-21 days", @first_time.scaled_time_interval
end
def test_oid_values
@ -47,10 +47,10 @@ def test_oid_values
end
def test_update_time
@first_time.time_interval = '2 years 3 minutes'
@first_time.time_interval = "2 years 3 minutes"
assert @first_time.save
assert @first_time.reload
assert_equal '2 years 00:03:00', @first_time.time_interval
assert_equal "2 years 00:03:00", @first_time.time_interval
end
def test_update_oid
@ -62,7 +62,7 @@ def test_update_oid
end
def test_text_columns_are_limitless_the_upper_limit_is_one_GB
assert_equal 'text', @connection.type_to_sql(:text, 100_000)
assert_equal "text", @connection.type_to_sql(:text, 100_000)
assert_raise ActiveRecord::ActiveRecordError do
@connection.type_to_sql :text, 4294967295
end
@ -77,15 +77,15 @@ class PostgresqlInternalDataTypeTest < ActiveRecord::PostgreSQLTestCase
end
def test_name_column_type
with_example_table @connection, 'ex', 'data name' do
column = @connection.columns('ex').find { |col| col.name == 'data' }
with_example_table @connection, "ex", "data name" do
column = @connection.columns("ex").find { |col| col.name == "data" }
assert_equal :string, column.type
end
end
def test_char_column_type
with_example_table @connection, 'ex', 'data "char"' do
column = @connection.columns('ex').find { |col| col.name == 'data' }
with_example_table @connection, "ex", 'data "char"' do
column = @connection.columns("ex").find { |col| col.name == "data" }
assert_equal :string, column.type
end
end

@ -1,5 +1,5 @@
require "cases/helper"
require 'support/connection_helper'
require "support/connection_helper"
class PostgresqlDomainTest < ActiveRecord::PostgreSQLTestCase
include ConnectionHelper
@ -12,15 +12,15 @@ def setup
@connection = ActiveRecord::Base.connection
@connection.transaction do
@connection.execute "CREATE DOMAIN custom_money as numeric(8,2)"
@connection.create_table('postgresql_domains') do |t|
@connection.create_table("postgresql_domains") do |t|
t.column :price, :custom_money
end
end
end
teardown do
@connection.drop_table 'postgresql_domains', if_exists: true
@connection.execute 'DROP DOMAIN IF EXISTS custom_money'
@connection.drop_table "postgresql_domains", if_exists: true
@connection.execute "DROP DOMAIN IF EXISTS custom_money"
reset_connection
end

@ -1,5 +1,5 @@
require "cases/helper"
require 'support/connection_helper'
require "support/connection_helper"
class PostgresqlEnumTest < ActiveRecord::PostgreSQLTestCase
include ConnectionHelper
@ -14,15 +14,15 @@ def setup
@connection.execute <<-SQL
CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');
SQL
@connection.create_table('postgresql_enums') do |t|
@connection.create_table("postgresql_enums") do |t|
t.column :current_mood, :mood
end
end
end
teardown do
@connection.drop_table 'postgresql_enums', if_exists: true
@connection.execute 'DROP TYPE IF EXISTS mood'
@connection.drop_table "postgresql_enums", if_exists: true
@connection.execute "DROP TYPE IF EXISTS mood"
reset_connection
end
@ -37,10 +37,10 @@ def test_column
end
def test_enum_defaults
@connection.add_column 'postgresql_enums', 'good_mood', :mood, default: 'happy'
@connection.add_column "postgresql_enums", "good_mood", :mood, default: "happy"
PostgresqlEnum.reset_column_information
assert_equal "happy", PostgresqlEnum.column_defaults['good_mood']
assert_equal "happy", PostgresqlEnum.column_defaults["good_mood"]
assert_equal "happy", PostgresqlEnum.new.good_mood
ensure
PostgresqlEnum.reset_column_information

@ -1,6 +1,6 @@
require "cases/helper"
require 'models/developer'
require 'models/computer'
require "models/developer"
require "models/computer"
class PostgreSQLExplainTest < ActiveRecord::PostgreSQLTestCase
fixtures :developers

@ -1,5 +1,5 @@
require "cases/helper"
require 'support/schema_dumping_helper'
require "support/schema_dumping_helper"
class PostgresqlFullTextTest < ActiveRecord::PostgreSQLTestCase
include SchemaDumpingHelper
@ -7,13 +7,13 @@ class Tsvector < ActiveRecord::Base; end
setup do
@connection = ActiveRecord::Base.connection
@connection.create_table('tsvectors') do |t|
t.tsvector 'text_vector'
@connection.create_table("tsvectors") do |t|
t.tsvector "text_vector"
end
end
teardown do
@connection.drop_table 'tsvectors', if_exists: true
@connection.drop_table "tsvectors", if_exists: true
end
def test_tsvector_column

@ -1,6 +1,6 @@
require "cases/helper"
require 'support/connection_helper'
require 'support/schema_dumping_helper'
require "support/connection_helper"
require "support/schema_dumping_helper"
class PostgresqlPointTest < ActiveRecord::PostgreSQLTestCase
include ConnectionHelper
@ -18,7 +18,7 @@ class PostgresqlPoint < ActiveRecord::Base
def setup
@connection = ActiveRecord::Base.connection
@connection.create_table('postgresql_points') do |t|
@connection.create_table("postgresql_points") do |t|
t.point :x
t.point :y, default: [12.2, 13.3]
t.point :z, default: "(14.4,15.5)"
@ -27,14 +27,14 @@ def setup
t.point :legacy_y, default: [12.2, 13.3]
t.point :legacy_z, default: "(14.4,15.5)"
end
@connection.create_table('deprecated_points') do |t|
@connection.create_table("deprecated_points") do |t|
t.point :x
end
end
teardown do
@connection.drop_table 'postgresql_points', if_exists: true
@connection.drop_table 'deprecated_points', if_exists: true
@connection.drop_table "postgresql_points", if_exists: true
@connection.drop_table "deprecated_points", if_exists: true
end
class DeprecatedPoint < ActiveRecord::Base; end
@ -56,10 +56,10 @@ def test_column
end
def test_default
assert_equal ActiveRecord::Point.new(12.2, 13.3), PostgresqlPoint.column_defaults['y']
assert_equal ActiveRecord::Point.new(12.2, 13.3), PostgresqlPoint.column_defaults["y"]
assert_equal ActiveRecord::Point.new(12.2, 13.3), PostgresqlPoint.new.y
assert_equal ActiveRecord::Point.new(14.4, 15.5), PostgresqlPoint.column_defaults['z']
assert_equal ActiveRecord::Point.new(14.4, 15.5), PostgresqlPoint.column_defaults["z"]
assert_equal ActiveRecord::Point.new(14.4, 15.5), PostgresqlPoint.new.z
end
@ -136,10 +136,10 @@ def test_legacy_column
end
def test_legacy_default
assert_equal [12.2, 13.3], PostgresqlPoint.column_defaults['legacy_y']
assert_equal [12.2, 13.3], PostgresqlPoint.column_defaults["legacy_y"]
assert_equal [12.2, 13.3], PostgresqlPoint.new.legacy_y
assert_equal [14.4, 15.5], PostgresqlPoint.column_defaults['legacy_z']
assert_equal [14.4, 15.5], PostgresqlPoint.column_defaults["legacy_z"]
assert_equal [14.4, 15.5], PostgresqlPoint.new.legacy_z
end
@ -190,51 +190,51 @@ class PostgresqlGeometric < ActiveRecord::Base; end
end
teardown do
@connection.drop_table 'postgresql_geometrics', if_exists: true
@connection.drop_table "postgresql_geometrics", if_exists: true
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!
h = PostgresqlGeometric.find(g.id)
assert_equal '[(2,3),(5.5,7)]', h.a_line_segment
assert_equal '(5.5,7),(2,3)', h.a_box # reordered to store upper right corner then bottom left corner
assert_equal '[(2,3),(5.5,7),(8.5,11)]', h.a_path
assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_polygon
assert_equal '<(5.3,10.4),2>', h.a_circle
assert_equal "[(2,3),(5.5,7)]", h.a_line_segment
assert_equal "(5.5,7),(2,3)", h.a_box # reordered to store upper right corner then bottom left corner
assert_equal "[(2,3),(5.5,7),(8.5,11)]", h.a_path
assert_equal "((2,3),(5.5,7),(8.5,11))", h.a_polygon
assert_equal "<(5.3,10.4),2>", h.a_circle
end
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!
h = PostgresqlGeometric.find(g.id)
assert_equal '[(2,3),(5.5,7)]', h.a_line_segment
assert_equal '(5.5,7),(2,3)', h.a_box # reordered to store upper right corner then bottom left corner
assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_path
assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_polygon
assert_equal '<(5.3,10.4),2>', h.a_circle
assert_equal "[(2,3),(5.5,7)]", h.a_line_segment
assert_equal "(5.5,7),(2,3)", h.a_box # reordered to store upper right corner then bottom left corner
assert_equal "((2,3),(5.5,7),(8.5,11))", h.a_path
assert_equal "((2,3),(5.5,7),(8.5,11))", h.a_polygon
assert_equal "<(5.3,10.4),2>", h.a_circle
end
def test_geometric_function
PostgresqlGeometric.create! a_path: '[(2.0, 3), (5.5, 7.0), (8.5, 11.0)]' # [ ] is an open path
PostgresqlGeometric.create! a_path: '((2.0, 3), (5.5, 7.0), (8.5, 11.0))' # ( ) is a closed path
PostgresqlGeometric.create! a_path: "[(2.0, 3), (5.5, 7.0), (8.5, 11.0)]" # [ ] is an open path
PostgresqlGeometric.create! a_path: "((2.0, 3), (5.5, 7.0), (8.5, 11.0))" # ( ) is a closed path
objs = PostgresqlGeometric.find_by_sql "SELECT isopen(a_path) FROM postgresql_geometrics ORDER BY id ASC"
assert_equal [true, false], objs.map(&:isopen)
@ -270,28 +270,28 @@ class PostgresqlLine < ActiveRecord::Base; end
teardown do
if defined?(@connection)
@connection.drop_table 'postgresql_lines', if_exists: true
@connection.drop_table "postgresql_lines", if_exists: true
end
end
def test_geometric_line_type
g = PostgresqlLine.new(
a_line: '{2.0, 3, 5.5}'
a_line: "{2.0, 3, 5.5}"
)
g.save!
h = PostgresqlLine.find(g.id)
assert_equal '{2,3,5.5}', h.a_line
assert_equal "{2,3,5.5}", h.a_line
end
def test_alternative_format_line_type
g = PostgresqlLine.new(
a_line: '(2.0, 3), (4.0, 6.0)'
a_line: "(2.0, 3), (4.0, 6.0)"
)
g.save!
h = PostgresqlLine.find(g.id)
assert_equal '{1.5,-1,0}', h.a_line
assert_equal "{1.5,-1,0}", h.a_line
end
def test_schema_dumping_for_line_type

@ -1,11 +1,11 @@
require "cases/helper"
require 'support/schema_dumping_helper'
require "support/schema_dumping_helper"
if ActiveRecord::Base.connection.supports_extensions?
class PostgresqlHstoreTest < ActiveRecord::PostgreSQLTestCase
include SchemaDumpingHelper
class Hstore < ActiveRecord::Base
self.table_name = 'hstores'
self.table_name = "hstores"
store_accessor :settings, :language, :timezone
end
@ -13,40 +13,40 @@ class Hstore < ActiveRecord::Base
def setup
@connection = ActiveRecord::Base.connection
unless @connection.extension_enabled?('hstore')
@connection.enable_extension 'hstore'
unless @connection.extension_enabled?("hstore")
@connection.enable_extension "hstore"
@connection.commit_db_transaction
end
@connection.reconnect!
@connection.transaction do
@connection.create_table('hstores') do |t|
t.hstore 'tags', :default => ''
t.hstore 'payload', array: true
t.hstore 'settings'
@connection.create_table("hstores") do |t|
t.hstore "tags", :default => ""
t.hstore "payload", array: true
t.hstore "settings"
end
end
Hstore.reset_column_information
@column = Hstore.columns_hash['tags']
@column = Hstore.columns_hash["tags"]
@type = Hstore.type_for_attribute("tags")
end
teardown do
@connection.drop_table 'hstores', if_exists: true
@connection.drop_table "hstores", if_exists: true
end
def test_hstore_included_in_extensions
assert @connection.respond_to?(:extensions), "connection should have a list of extensions"
assert @connection.extensions.include?('hstore'), "extension list should include hstore"
assert @connection.extensions.include?("hstore"), "extension list should include hstore"
end
def test_disable_enable_hstore
assert @connection.extension_enabled?('hstore')
@connection.disable_extension 'hstore'
assert_not @connection.extension_enabled?('hstore')
@connection.enable_extension 'hstore'
assert @connection.extension_enabled?('hstore')
assert @connection.extension_enabled?("hstore")
@connection.disable_extension "hstore"
assert_not @connection.extension_enabled?("hstore")
@connection.enable_extension "hstore"
assert @connection.extension_enabled?("hstore")
ensure
# Restore column(s) dropped by `drop extension hstore cascade;`
load_schema
@ -61,10 +61,10 @@ def test_column
end
def test_default
@connection.add_column 'hstores', 'permissions', :hstore, default: '"users"=>"read", "articles"=>"write"'
@connection.add_column "hstores", "permissions", :hstore, default: '"users"=>"read", "articles"=>"write"'
Hstore.reset_column_information
assert_equal({"users"=>"read", "articles"=>"write"}, Hstore.column_defaults['permissions'])
assert_equal({"users"=>"read", "articles"=>"write"}, Hstore.column_defaults["permissions"])
assert_equal({"users"=>"read", "articles"=>"write"}, Hstore.new.permissions)
ensure
Hstore.reset_column_information
@ -72,11 +72,11 @@ def test_default
def test_change_table_supports_hstore
@connection.transaction do
@connection.change_table('hstores') do |t|
t.hstore 'users', default: ''
@connection.change_table("hstores") do |t|
t.hstore "users", default: ""
end
Hstore.reset_column_information
column = Hstore.columns_hash['users']
column = Hstore.columns_hash["users"]
assert_equal :hstore, column.type
raise ActiveRecord::Rollback # reset the schema change
@ -111,10 +111,10 @@ def test_cast_value_on_write
end
def test_type_cast_hstore
assert_equal({'1' => '2'}, @type.deserialize("\"1\"=>\"2\""))
assert_equal({"1" => "2"}, @type.deserialize("\"1\"=>\"2\""))
assert_equal({}, @type.deserialize(""))
assert_equal({'key'=>nil}, @type.deserialize('key => NULL'))
assert_equal({'c'=>'}','"a"'=>'b "a b'}, @type.deserialize(%q(c=>"}", "\"a\""=>"b \"a b")))
assert_equal({"key"=>nil}, @type.deserialize("key => NULL"))
assert_equal({"c"=>"}",'"a"'=>'b "a b'}, @type.deserialize(%q(c=>"}", "\"a\""=>"b \"a b")))
end
def test_with_store_accessors
@ -156,33 +156,33 @@ def test_yaml_round_trip_with_store_accessors
end
def test_changes_in_place
hstore = Hstore.create!(settings: { 'one' => 'two' })
hstore.settings['three'] = 'four'
hstore = Hstore.create!(settings: { "one" => "two" })
hstore.settings["three"] = "four"
hstore.save!
hstore.reload
assert_equal 'four', hstore.settings['three']
assert_equal "four", hstore.settings["three"]
assert_not hstore.changed?
end
def test_gen1
assert_equal(%q(" "=>""), @type.serialize({' '=>''}))
assert_equal(%q(" "=>""), @type.serialize({" "=>""}))
end
def test_gen2
assert_equal(%q(","=>""), @type.serialize({','=>''}))
assert_equal(%q(","=>""), @type.serialize({","=>""}))
end
def test_gen3
assert_equal(%q("="=>""), @type.serialize({'='=>''}))
assert_equal(%q("="=>""), @type.serialize({"="=>""}))
end
def test_gen4
assert_equal(%q(">"=>""), @type.serialize({'>'=>''}))
assert_equal(%q(">"=>""), @type.serialize({">"=>""}))
end
def test_parse1
assert_equal({'a'=>nil,'b'=>nil,'c'=>'NuLl','null'=>'c'}, @type.deserialize('a=>null,b=>NuLl,c=>"NuLl",null=>c'))
assert_equal({"a"=>nil,"b"=>nil,"c"=>"NuLl","null"=>"c"}, @type.deserialize('a=>null,b=>NuLl,c=>"NuLl",null=>c'))
end
def test_parse2
@ -212,14 +212,14 @@ def test_parse7
def test_rewrite
@connection.execute "insert into hstores (tags) VALUES ('1=>2')"
x = Hstore.first
x.tags = { '"a\'' => 'b' }
x.tags = { '"a\'' => "b" }
assert x.save!
end
def test_select
@connection.execute "insert into hstores (tags) VALUES ('1=>2')"
x = Hstore.first
assert_equal({'1' => '2'}, x.tags)
assert_equal({"1" => "2"}, x.tags)
end
def test_array_cycle
@ -227,61 +227,61 @@ def test_array_cycle
end
def test_array_strings_with_quotes
assert_array_cycle([{'this has' => 'some "s that need to be escaped"'}])
assert_array_cycle([{"this has" => 'some "s that need to be escaped"'}])
end
def test_array_strings_with_commas
assert_array_cycle([{'this,has' => 'many,values'}])
assert_array_cycle([{"this,has" => "many,values"}])
end
def test_array_strings_with_array_delimiters
assert_array_cycle(['{' => '}'])
assert_array_cycle(["{" => "}"])
end
def test_array_strings_with_null_strings
assert_array_cycle([{'NULL' => 'NULL'}])
assert_array_cycle([{"NULL" => "NULL"}])
end
def test_contains_nils
assert_array_cycle([{'NULL' => nil}])
assert_array_cycle([{"NULL" => nil}])
end
def test_select_multikey
@connection.execute "insert into hstores (tags) VALUES ('1=>2,2=>3')"
x = Hstore.first
assert_equal({'1' => '2', '2' => '3'}, x.tags)
assert_equal({"1" => "2", "2" => "3"}, x.tags)
end
def test_create
assert_cycle('a' => 'b', '1' => '2')
assert_cycle("a" => "b", "1" => "2")
end
def test_nil
assert_cycle('a' => nil)
assert_cycle("a" => nil)
end
def test_quotes
assert_cycle('a' => 'b"ar', '1"foo' => '2')
assert_cycle("a" => 'b"ar', '1"foo' => "2")
end
def test_whitespace
assert_cycle('a b' => 'b ar', '1"foo' => '2')
assert_cycle("a b" => "b ar", '1"foo' => "2")
end
def test_backslash
assert_cycle('a\\b' => 'b\\ar', '1"foo' => '2')
assert_cycle('a\\b' => 'b\\ar', '1"foo' => "2")
end
def test_comma
assert_cycle('a, b' => 'bar', '1"foo' => '2')
assert_cycle("a, b" => "bar", '1"foo' => "2")
end
def test_arrow
assert_cycle('a=>b' => 'bar', '1"foo' => '2')
assert_cycle("a=>b" => "bar", '1"foo' => "2")
end
def test_quoting_special_characters
assert_cycle('ca' => 'cà', 'ac' => 'àc')
assert_cycle("ca" => "", "ac" => "àc")
end
def test_multiline

@ -15,7 +15,7 @@ class PostgresqlInfinity < ActiveRecord::Base
end
teardown do
@connection.drop_table 'postgresql_infinities', if_exists: true
@connection.drop_table "postgresql_infinities", if_exists: true
end
test "type casting infinity on a float column" do
@ -25,11 +25,11 @@ class PostgresqlInfinity < ActiveRecord::Base
end
test "type casting string on a float column" do
record = PostgresqlInfinity.new(float: 'Infinity')
record = PostgresqlInfinity.new(float: "Infinity")
assert_equal Float::INFINITY, record.float
record = PostgresqlInfinity.new(float: '-Infinity')
record = PostgresqlInfinity.new(float: "-Infinity")
assert_equal(-Float::INFINITY, record.float)
record = PostgresqlInfinity.new(float: 'NaN')
record = PostgresqlInfinity.new(float: "NaN")
assert_send [record.float, :nan?]
end

@ -1,11 +1,11 @@
require "cases/helper"
require 'support/schema_dumping_helper'
require "support/schema_dumping_helper"
module PostgresqlJSONSharedTestCases
include SchemaDumpingHelper
class JsonDataType < ActiveRecord::Base
self.table_name = 'json_data_type'
self.table_name = "json_data_type"
store_accessor :settings, :resolution
end
@ -13,9 +13,9 @@ class JsonDataType < ActiveRecord::Base
def setup
@connection = ActiveRecord::Base.connection
begin
@connection.create_table('json_data_type') do |t|
t.public_send column_type, 'payload', default: {} # t.json 'payload', default: {}
t.public_send column_type, 'settings' # t.json 'settings'
@connection.create_table("json_data_type") do |t|
t.public_send column_type, "payload", default: {} # t.json 'payload', default: {}
t.public_send column_type, "settings" # t.json 'settings'
end
rescue ActiveRecord::StatementInvalid
skip "do not test on PostgreSQL without #{column_type} type."
@ -38,10 +38,10 @@ def test_column
end
def test_default
@connection.add_column 'json_data_type', 'permissions', column_type, default: {"users": "read", "posts": ["read", "write"]}
@connection.add_column "json_data_type", "permissions", column_type, default: {"users": "read", "posts": ["read", "write"]}
JsonDataType.reset_column_information
assert_equal({"users"=>"read", "posts"=>["read", "write"]}, JsonDataType.column_defaults['permissions'])
assert_equal({"users"=>"read", "posts"=>["read", "write"]}, JsonDataType.column_defaults["permissions"])
assert_equal({"users"=>"read", "posts"=>["read", "write"]}, JsonDataType.new.permissions)
ensure
JsonDataType.reset_column_information
@ -49,11 +49,11 @@ def test_default
def test_change_table_supports_json
@connection.transaction do
@connection.change_table('json_data_type') do |t|
t.public_send column_type, 'users', default: '{}' # t.json 'users', default: '{}'
@connection.change_table("json_data_type") do |t|
t.public_send column_type, "users", default: "{}" # t.json 'users', default: '{}'
end
JsonDataType.reset_column_information
column = JsonDataType.columns_hash['users']
column = JsonDataType.columns_hash["users"]
assert_equal column_type, column.type
raise ActiveRecord::Rollback # reset the schema change
@ -80,31 +80,31 @@ def test_type_cast_json
data = "{\"a_key\":\"a_value\"}"
hash = type.deserialize(data)
assert_equal({'a_key' => 'a_value'}, hash)
assert_equal({'a_key' => 'a_value'}, type.deserialize(data))
assert_equal({"a_key" => "a_value"}, hash)
assert_equal({"a_key" => "a_value"}, type.deserialize(data))
assert_equal({}, type.deserialize("{}"))
assert_equal({'key'=>nil}, type.deserialize('{"key": null}'))
assert_equal({'c'=>'}','"a"'=>'b "a b'}, type.deserialize(%q({"c":"}", "\"a\"":"b \"a b"})))
assert_equal({"key"=>nil}, type.deserialize('{"key": null}'))
assert_equal({"c"=>"}",'"a"'=>'b "a b'}, type.deserialize(%q({"c":"}", "\"a\"":"b \"a b"})))
end
def test_rewrite
@connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')"
x = JsonDataType.first
x.payload = { '"a\'' => 'b' }
x.payload = { '"a\'' => "b" }
assert x.save!
end
def test_select
@connection.execute "insert into json_data_type (payload) VALUES ('{\"k\":\"v\"}')"
x = JsonDataType.first
assert_equal({'k' => 'v'}, x.payload)
assert_equal({"k" => "v"}, x.payload)
end
def test_select_multikey
@connection.execute %q|insert into json_data_type (payload) VALUES ('{"k1":"v1", "k2":"v2", "k3":[1,2,3]}')|
x = JsonDataType.first
assert_equal({'k1' => 'v1', 'k2' => 'v2', 'k3' => [1,2,3]}, x.payload)
assert_equal({"k1" => "v1", "k2" => "v2", "k3" => [1,2,3]}, x.payload)
end
def test_null_json
@ -116,13 +116,13 @@ def test_null_json
def test_select_array_json_value
@connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')|
x = JsonDataType.first
assert_equal(['v0', {'k1' => 'v1'}], x.payload)
assert_equal(["v0", {"k1" => "v1"}], x.payload)
end
def test_rewrite_array_json_value
@connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')|
x = JsonDataType.first
x.payload = ['v1', {'k2' => 'v2'}, 'v3']
x.payload = ["v1", {"k2" => "v2"}, "v3"]
assert x.save!
end
@ -161,20 +161,20 @@ def test_changes_in_place
json = JsonDataType.new
assert_not json.changed?
json.payload = { 'one' => 'two' }
json.payload = { "one" => "two" }
assert json.changed?
assert json.payload_changed?
json.save!
assert_not json.changed?
json.payload['three'] = 'four'
json.payload["three"] = "four"
assert json.payload_changed?
json.save!
json.reload
assert_equal({ 'one' => 'two', 'three' => 'four' }, json.payload)
assert_equal({ "one" => "two", "three" => "four" }, json.payload)
assert_not json.changed?
end

@ -1,20 +1,20 @@
require "cases/helper"
require 'support/schema_dumping_helper'
require "support/schema_dumping_helper"
class PostgresqlLtreeTest < ActiveRecord::PostgreSQLTestCase
include SchemaDumpingHelper
class Ltree < ActiveRecord::Base
self.table_name = 'ltrees'
self.table_name = "ltrees"
end
def setup
@connection = ActiveRecord::Base.connection
enable_extension!('ltree', @connection)
enable_extension!("ltree", @connection)
@connection.transaction do
@connection.create_table('ltrees') do |t|
t.ltree 'path'
@connection.create_table("ltrees") do |t|
t.ltree "path"
end
end
rescue ActiveRecord::StatementInvalid
@ -22,28 +22,28 @@ def setup
end
teardown do
@connection.drop_table 'ltrees', if_exists: true
@connection.drop_table "ltrees", if_exists: true
end
def test_column
column = Ltree.columns_hash['path']
column = Ltree.columns_hash["path"]
assert_equal :ltree, column.type
assert_equal "ltree", column.sql_type
assert_not column.array?
type = Ltree.type_for_attribute('path')
type = Ltree.type_for_attribute("path")
assert_not type.binary?
end
def test_write
ltree = Ltree.new(path: '1.2.3.4')
ltree = Ltree.new(path: "1.2.3.4")
assert ltree.save!
end
def test_select
@connection.execute "insert into ltrees (path) VALUES ('1.2.3')"
ltree = Ltree.first
assert_equal '1.2.3', ltree.path
assert_equal "1.2.3", ltree.path
end
def test_schema_dump_with_shorthand

@ -1,5 +1,5 @@
require "cases/helper"
require 'support/schema_dumping_helper'
require "support/schema_dumping_helper"
class PostgresqlMoneyTest < ActiveRecord::PostgreSQLTestCase
include SchemaDumpingHelper
@ -9,14 +9,14 @@ class PostgresqlMoney < ActiveRecord::Base; end
setup do
@connection = ActiveRecord::Base.connection
@connection.execute("set lc_monetary = 'C'")
@connection.create_table('postgresql_moneys', force: true) do |t|
@connection.create_table("postgresql_moneys", force: true) do |t|
t.money "wealth"
t.money "depth", default: "150.55"
end
end
teardown do
@connection.drop_table 'postgresql_moneys', if_exists: true
@connection.drop_table "postgresql_moneys", if_exists: true
end
def test_column
@ -31,7 +31,7 @@ def test_column
end
def test_default
assert_equal BigDecimal.new("150.55"), PostgresqlMoney.column_defaults['depth']
assert_equal BigDecimal.new("150.55"), PostgresqlMoney.column_defaults["depth"]
assert_equal BigDecimal.new("150.55"), PostgresqlMoney.new.depth
end
@ -46,7 +46,7 @@ def test_money_values
end
def test_money_type_cast
type = PostgresqlMoney.type_for_attribute('wealth')
type = PostgresqlMoney.type_for_attribute("wealth")
assert_equal(12345678.12, type.cast("$12,345,678.12"))
assert_equal(12345678.12, type.cast("$12.345.678,12"))
assert_equal(-1.15, type.cast("-$1.15"))
@ -63,7 +63,7 @@ def test_create_and_update_money
money = PostgresqlMoney.create(wealth: "987.65")
assert_equal 987.65, money.wealth
new_value = BigDecimal.new('123.45')
new_value = BigDecimal.new("123.45")
money.wealth = new_value
money.save!
money.reload
@ -80,7 +80,7 @@ def test_update_all_with_money_string
def test_update_all_with_money_big_decimal
money = PostgresqlMoney.create!
PostgresqlMoney.update_all(wealth: '123.45'.to_d)
PostgresqlMoney.update_all(wealth: "123.45".to_d)
money.reload
assert_equal 123.45, money.wealth

@ -1,5 +1,5 @@
require "cases/helper"
require 'support/schema_dumping_helper'
require "support/schema_dumping_helper"
class PostgresqlNetworkTest < ActiveRecord::PostgreSQLTestCase
include SchemaDumpingHelper
@ -7,15 +7,15 @@ class PostgresqlNetworkAddress < ActiveRecord::Base; end
setup do
@connection = ActiveRecord::Base.connection
@connection.create_table('postgresql_network_addresses', force: true) do |t|
t.inet 'inet_address', default: "192.168.1.1"
t.cidr 'cidr_address', default: "192.168.1.0/24"
t.macaddr 'mac_address', default: "ff:ff:ff:ff:ff:ff"
@connection.create_table("postgresql_network_addresses", force: true) do |t|
t.inet "inet_address", default: "192.168.1.1"
t.cidr "cidr_address", default: "192.168.1.0/24"
t.macaddr "mac_address", default: "ff:ff:ff:ff:ff:ff"
end
end
teardown do
@connection.drop_table 'postgresql_network_addresses', if_exists: true
@connection.drop_table "postgresql_network_addresses", if_exists: true
end
def test_cidr_column
@ -49,33 +49,33 @@ def test_macaddr_column
end
def test_network_types
PostgresqlNetworkAddress.create(cidr_address: '192.168.0.0/24',
inet_address: '172.16.1.254/32',
mac_address: '01:23:45:67:89:0a')
PostgresqlNetworkAddress.create(cidr_address: "192.168.0.0/24",
inet_address: "172.16.1.254/32",
mac_address: "01:23:45:67:89:0a")
address = PostgresqlNetworkAddress.first
assert_equal IPAddr.new('192.168.0.0/24'), address.cidr_address
assert_equal IPAddr.new('172.16.1.254'), address.inet_address
assert_equal '01:23:45:67:89:0a', address.mac_address
assert_equal IPAddr.new("192.168.0.0/24"), address.cidr_address
assert_equal IPAddr.new("172.16.1.254"), address.inet_address
assert_equal "01:23:45:67:89:0a", address.mac_address
address.cidr_address = '10.1.2.3/32'
address.inet_address = '10.0.0.0/8'
address.mac_address = 'bc:de:f0:12:34:56'
address.cidr_address = "10.1.2.3/32"
address.inet_address = "10.0.0.0/8"
address.mac_address = "bc:de:f0:12:34:56"
address.save!
assert address.reload
assert_equal IPAddr.new('10.1.2.3/32'), address.cidr_address
assert_equal IPAddr.new('10.0.0.0/8'), address.inet_address
assert_equal 'bc:de:f0:12:34:56', address.mac_address
assert_equal IPAddr.new("10.1.2.3/32"), address.cidr_address
assert_equal IPAddr.new("10.0.0.0/8"), address.inet_address
assert_equal "bc:de:f0:12:34:56", address.mac_address
end
def test_invalid_network_address
invalid_address = PostgresqlNetworkAddress.new(cidr_address: 'invalid addr',
inet_address: 'invalid addr')
invalid_address = PostgresqlNetworkAddress.new(cidr_address: "invalid addr",
inet_address: "invalid addr")
assert_nil invalid_address.cidr_address
assert_nil invalid_address.inet_address
assert_equal 'invalid addr', invalid_address.cidr_address_before_type_cast
assert_equal 'invalid addr', invalid_address.inet_address_before_type_cast
assert_equal "invalid addr", invalid_address.cidr_address_before_type_cast
assert_equal "invalid addr", invalid_address.inet_address_before_type_cast
assert invalid_address.save
invalid_address.reload

@ -5,14 +5,14 @@ class PostgresqlNumber < ActiveRecord::Base; end
setup do
@connection = ActiveRecord::Base.connection
@connection.create_table('postgresql_numbers', force: true) do |t|
t.column 'single', 'REAL'
t.column 'double', 'DOUBLE PRECISION'
@connection.create_table("postgresql_numbers", force: true) do |t|
t.column "single", "REAL"
t.column "double", "DOUBLE PRECISION"
end
end
teardown do
@connection.drop_table 'postgresql_numbers', if_exists: true
@connection.drop_table "postgresql_numbers", if_exists: true
end
def test_data_type

@ -1,6 +1,6 @@
require "cases/helper"
require 'support/ddl_helper'
require 'support/connection_helper'
require "support/ddl_helper"
require "support/connection_helper"
module ActiveRecord
module ConnectionAdapters
@ -15,15 +15,15 @@ def setup
def test_bad_connection
assert_raise ActiveRecord::NoDatabaseError do
configuration = ActiveRecord::Base.configurations['arunit'].merge(database: 'should_not_exist-cinco-dog-db')
configuration = ActiveRecord::Base.configurations["arunit"].merge(database: "should_not_exist-cinco-dog-db")
connection = ActiveRecord::Base.postgresql_connection(configuration)
connection.exec_query('SELECT 1')
connection.exec_query("SELECT 1")
end
end
def test_valid_column
with_example_table do
column = @connection.columns('ex').find { |col| col.name == 'id' }
column = @connection.columns("ex").find { |col| col.name == "id" }
assert @connection.valid_type?(column.type)
end
end
@ -34,144 +34,144 @@ def test_invalid_column
def test_primary_key
with_example_table do
assert_equal 'id', @connection.primary_key('ex')
assert_equal "id", @connection.primary_key("ex")
end
end
def test_primary_key_works_tables_containing_capital_letters
assert_equal 'id', @connection.primary_key('CamelCase')
assert_equal "id", @connection.primary_key("CamelCase")
end
def test_non_standard_primary_key
with_example_table 'data character varying(255) primary key' do
assert_equal 'data', @connection.primary_key('ex')
with_example_table "data character varying(255) primary key" do
assert_equal "data", @connection.primary_key("ex")
end
end
def test_primary_key_returns_nil_for_no_pk
with_example_table 'id integer' do
assert_nil @connection.primary_key('ex')
with_example_table "id integer" do
assert_nil @connection.primary_key("ex")
end
end
def test_primary_key_raises_error_if_table_not_found
assert_raises(ActiveRecord::StatementInvalid) do
@connection.primary_key('unobtainium')
@connection.primary_key("unobtainium")
end
end
def test_exec_insert_with_returning_disabled
connection = connection_without_insert_returning
result = connection.exec_insert("insert into postgresql_partitioned_table_parent (number) VALUES (1)", nil, [], 'id', 'postgresql_partitioned_table_parent_id_seq')
expect = connection.query('select max(id) from postgresql_partitioned_table_parent').first.first
result = connection.exec_insert("insert into postgresql_partitioned_table_parent (number) VALUES (1)", nil, [], "id", "postgresql_partitioned_table_parent_id_seq")
expect = connection.query("select max(id) from postgresql_partitioned_table_parent").first.first
assert_equal expect.to_i, result.rows.first.first
end
def test_exec_insert_with_returning_disabled_and_no_sequence_name_given
connection = connection_without_insert_returning
result = connection.exec_insert("insert into postgresql_partitioned_table_parent (number) VALUES (1)", nil, [], 'id')
expect = connection.query('select max(id) from postgresql_partitioned_table_parent').first.first
result = connection.exec_insert("insert into postgresql_partitioned_table_parent (number) VALUES (1)", nil, [], "id")
expect = connection.query("select max(id) from postgresql_partitioned_table_parent").first.first
assert_equal expect.to_i, result.rows.first.first
end
def test_exec_insert_default_values_with_returning_disabled_and_no_sequence_name_given
connection = connection_without_insert_returning
result = connection.exec_insert("insert into postgresql_partitioned_table_parent DEFAULT VALUES", nil, [], 'id')
expect = connection.query('select max(id) from postgresql_partitioned_table_parent').first.first
result = connection.exec_insert("insert into postgresql_partitioned_table_parent DEFAULT VALUES", nil, [], "id")
expect = connection.query("select max(id) from postgresql_partitioned_table_parent").first.first
assert_equal expect.to_i, result.rows.first.first
end
def test_exec_insert_default_values_quoted_schema_with_returning_disabled_and_no_sequence_name_given
connection = connection_without_insert_returning
result = connection.exec_insert('insert into "public"."postgresql_partitioned_table_parent" DEFAULT VALUES', nil, [], 'id')
expect = connection.query('select max(id) from postgresql_partitioned_table_parent').first.first
result = connection.exec_insert('insert into "public"."postgresql_partitioned_table_parent" DEFAULT VALUES', nil, [], "id")
expect = connection.query("select max(id) from postgresql_partitioned_table_parent").first.first
assert_equal expect.to_i, result.rows.first.first
end
def test_sql_for_insert_with_returning_disabled
connection = connection_without_insert_returning
sql, binds = connection.sql_for_insert('sql', nil, nil, nil, 'binds')
assert_equal ['sql', 'binds'], [sql, binds]
sql, binds = connection.sql_for_insert("sql", nil, nil, nil, "binds")
assert_equal ["sql", "binds"], [sql, binds]
end
def test_serial_sequence
assert_equal 'public.accounts_id_seq',
@connection.serial_sequence('accounts', 'id')
assert_equal "public.accounts_id_seq",
@connection.serial_sequence("accounts", "id")
assert_raises(ActiveRecord::StatementInvalid) do
@connection.serial_sequence('zomg', 'id')
@connection.serial_sequence("zomg", "id")
end
end
def test_default_sequence_name
assert_equal 'public.accounts_id_seq',
@connection.default_sequence_name('accounts', 'id')
assert_equal "public.accounts_id_seq",
@connection.default_sequence_name("accounts", "id")
assert_equal 'public.accounts_id_seq',
@connection.default_sequence_name('accounts')
assert_equal "public.accounts_id_seq",
@connection.default_sequence_name("accounts")
end
def test_default_sequence_name_bad_table
assert_equal 'zomg_id_seq',
@connection.default_sequence_name('zomg', 'id')
assert_equal "zomg_id_seq",
@connection.default_sequence_name("zomg", "id")
assert_equal 'zomg_id_seq',
@connection.default_sequence_name('zomg')
assert_equal "zomg_id_seq",
@connection.default_sequence_name("zomg")
end
def test_pk_and_sequence_for
with_example_table do
pk, seq = @connection.pk_and_sequence_for('ex')
assert_equal 'id', pk
assert_equal @connection.default_sequence_name('ex', 'id'), seq.to_s
pk, seq = @connection.pk_and_sequence_for("ex")
assert_equal "id", pk
assert_equal @connection.default_sequence_name("ex", "id"), seq.to_s
end
end
def test_pk_and_sequence_for_with_non_standard_primary_key
with_example_table 'code serial primary key' do
pk, seq = @connection.pk_and_sequence_for('ex')
assert_equal 'code', pk
assert_equal @connection.default_sequence_name('ex', 'code'), seq.to_s
with_example_table "code serial primary key" do
pk, seq = @connection.pk_and_sequence_for("ex")
assert_equal "code", pk
assert_equal @connection.default_sequence_name("ex", "code"), seq.to_s
end
end
def test_pk_and_sequence_for_returns_nil_if_no_seq
with_example_table 'id integer primary key' do
assert_nil @connection.pk_and_sequence_for('ex')
with_example_table "id integer primary key" do
assert_nil @connection.pk_and_sequence_for("ex")
end
end
def test_pk_and_sequence_for_returns_nil_if_no_pk
with_example_table 'id integer' do
assert_nil @connection.pk_and_sequence_for('ex')
with_example_table "id integer" do
assert_nil @connection.pk_and_sequence_for("ex")
end
end
def test_pk_and_sequence_for_returns_nil_if_table_not_found
assert_nil @connection.pk_and_sequence_for('unobtainium')
assert_nil @connection.pk_and_sequence_for("unobtainium")
end
def test_pk_and_sequence_for_with_collision_pg_class_oid
@connection.exec_query('create table ex(id serial primary key)')
@connection.exec_query('create table ex2(id serial primary key)')
@connection.exec_query("create table ex(id serial primary key)")
@connection.exec_query("create table ex2(id serial primary key)")
correct_depend_record = [
"'pg_class'::regclass",
"'ex_id_seq'::regclass",
'0',
"0",
"'pg_class'::regclass",
"'ex'::regclass",
'1',
"1",
"'a'"
]
collision_depend_record = [
"'pg_attrdef'::regclass",
"'ex2_id_seq'::regclass",
'0',
"0",
"'pg_class'::regclass",
"'ex'::regclass",
'1',
"1",
"'a'"
]
@ -185,15 +185,15 @@ def test_pk_and_sequence_for_with_collision_pg_class_oid
"INSERT INTO pg_depend VALUES(#{correct_depend_record.join(',')})"
)
seq = @connection.pk_and_sequence_for('ex').last
seq = @connection.pk_and_sequence_for("ex").last
assert_equal PostgreSQL::Name.new("public", "ex_id_seq"), seq
@connection.exec_query(
"DELETE FROM pg_depend WHERE objid = 'ex2_id_seq'::regclass AND refobjid = 'ex'::regclass AND deptype = 'a'"
)
ensure
@connection.drop_table 'ex', if_exists: true
@connection.drop_table 'ex2', if_exists: true
@connection.drop_table "ex", if_exists: true
@connection.drop_table "ex2", if_exists: true
end
def test_table_alias_length
@ -204,74 +204,74 @@ def test_table_alias_length
def test_exec_no_binds
with_example_table do
result = @connection.exec_query('SELECT id, data FROM ex')
result = @connection.exec_query("SELECT id, data FROM ex")
assert_equal 0, result.rows.length
assert_equal 2, result.columns.length
assert_equal %w{ id data }, result.columns
string = @connection.quote('foo')
string = @connection.quote("foo")
@connection.exec_query("INSERT INTO ex (id, data) VALUES (1, #{string})")
result = @connection.exec_query('SELECT id, data FROM ex')
result = @connection.exec_query("SELECT id, data FROM ex")
assert_equal 1, result.rows.length
assert_equal 2, result.columns.length
assert_equal [[1, 'foo']], result.rows
assert_equal [[1, "foo"]], result.rows
end
end
if ActiveRecord::Base.connection.prepared_statements
def test_exec_with_binds
with_example_table do
string = @connection.quote('foo')
string = @connection.quote("foo")
@connection.exec_query("INSERT INTO ex (id, data) VALUES (1, #{string})")
bind = Relation::QueryAttribute.new("id", 1, Type::Value.new)
result = @connection.exec_query('SELECT id, data FROM ex WHERE id = $1', nil, [bind])
result = @connection.exec_query("SELECT id, data FROM ex WHERE id = $1", nil, [bind])
assert_equal 1, result.rows.length
assert_equal 2, result.columns.length
assert_equal [[1, 'foo']], result.rows
assert_equal [[1, "foo"]], result.rows
end
end
def test_exec_typecasts_bind_vals
with_example_table do
string = @connection.quote('foo')
string = @connection.quote("foo")
@connection.exec_query("INSERT INTO ex (id, data) VALUES (1, #{string})")
bind = Relation::QueryAttribute.new("id", "1-fuu", Type::Integer.new)
result = @connection.exec_query('SELECT id, data FROM ex WHERE id = $1', nil, [bind])
result = @connection.exec_query("SELECT id, data FROM ex WHERE id = $1", nil, [bind])
assert_equal 1, result.rows.length
assert_equal 2, result.columns.length
assert_equal [[1, 'foo']], result.rows
assert_equal [[1, "foo"]], result.rows
end
end
end
def test_partial_index
with_example_table do
@connection.add_index 'ex', %w{ id number }, :name => 'partial', :where => "number > 100"
index = @connection.indexes('ex').find { |idx| idx.name == 'partial' }
@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
end
def test_expression_index
with_example_table do
@connection.add_index 'ex', 'mod(id, 10), abs(number)', name: 'expression'
index = @connection.indexes('ex').find { |idx| idx.name == 'expression' }
assert_equal 'mod(id, 10), abs(number)', index.columns
@connection.add_index "ex", "mod(id, 10), abs(number)", name: "expression"
index = @connection.indexes("ex").find { |idx| idx.name == "expression" }
assert_equal "mod(id, 10), abs(number)", index.columns
end
end
def test_index_with_opclass
with_example_table do
@connection.add_index 'ex', 'data varchar_pattern_ops', name: 'with_opclass'
index = @connection.indexes('ex').find { |idx| idx.name == 'with_opclass' }
assert_equal 'data varchar_pattern_ops', index.columns
@connection.add_index "ex", "data varchar_pattern_ops", name: "with_opclass"
index = @connection.indexes("ex").find { |idx| idx.name == "with_opclass" }
assert_equal "data varchar_pattern_ops", index.columns
end
end
@ -292,8 +292,8 @@ def test_columns_for_distinct_few_orders
def test_columns_for_distinct_with_case
assert_equal(
'posts.id, CASE WHEN author.is_active THEN UPPER(author.name) ELSE UPPER(author.email) END AS alias_0',
@connection.columns_for_distinct('posts.id',
"posts.id, CASE WHEN author.is_active THEN UPPER(author.name) ELSE UPPER(author.email) END AS alias_0",
@connection.columns_for_distinct("posts.id",
["CASE WHEN author.is_active THEN UPPER(author.name) ELSE UPPER(author.email) END"])
)
end
@ -374,7 +374,7 @@ def test_only_warn_on_first_encounter_of_unknown_oid
def test_unparsed_defaults_are_at_least_set_when_saving
with_example_table "id SERIAL PRIMARY KEY, number INTEGER NOT NULL DEFAULT (4 + 4) * 2 / 4" do
number_klass = Class.new(ActiveRecord::Base) do
self.table_name = 'ex'
self.table_name = "ex"
end
column = number_klass.columns_hash["number"]
assert_nil column.default
@ -390,12 +390,12 @@ def test_unparsed_defaults_are_at_least_set_when_saving
private
def with_example_table(definition = 'id serial primary key, number integer, data character varying(255)', &block)
super(@connection, 'ex', definition, &block)
def with_example_table(definition = "id serial primary key, number integer, data character varying(255)", &block)
super(@connection, "ex", definition, &block)
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

@ -1,5 +1,5 @@
require "cases/helper"
require 'ipaddr'
require "ipaddr"
module ActiveRecord
module ConnectionAdapters
@ -10,11 +10,11 @@ def setup
end
def test_type_cast_true
assert_equal 't', @conn.type_cast(true)
assert_equal "t", @conn.type_cast(true)
end
def test_type_cast_false
assert_equal 'f', @conn.type_cast(false)
assert_equal "f", @conn.type_cast(false)
end
def test_quote_float_nan

@ -1,5 +1,5 @@
require "cases/helper"
require 'support/connection_helper'
require "support/connection_helper"
if ActiveRecord::Base.connection.respond_to?(:supports_ranges?) && ActiveRecord::Base.connection.supports_ranges?
class PostgresqlRange < ActiveRecord::Base
@ -23,7 +23,7 @@ def setup
);
_SQL
@connection.create_table('postgresql_ranges') do |t|
@connection.create_table("postgresql_ranges") do |t|
t.daterange :date_range
t.numrange :num_range
t.tsrange :ts_range
@ -32,7 +32,7 @@ def setup
t.int8range :int8_range
end
@connection.add_column 'postgresql_ranges', 'float_range', 'floatrange'
@connection.add_column "postgresql_ranges", "float_range", "floatrange"
end
PostgresqlRange.reset_column_information
rescue ActiveRecord::StatementInvalid
@ -93,8 +93,8 @@ def setup
end
teardown do
@connection.drop_table 'postgresql_ranges', if_exists: true
@connection.execute 'DROP TYPE IF EXISTS floatrange'
@connection.drop_table "postgresql_ranges", if_exists: true
@connection.execute "DROP TYPE IF EXISTS floatrange"
reset_connection
end
@ -132,10 +132,10 @@ def test_daterange_values
end
def test_numrange_values
assert_equal BigDecimal.new('0.1')..BigDecimal.new('0.2'), @first_range.num_range
assert_equal BigDecimal.new('0.1')...BigDecimal.new('0.2'), @second_range.num_range
assert_equal BigDecimal.new('0.1')...BigDecimal.new('Infinity'), @third_range.num_range
assert_equal BigDecimal.new('-Infinity')...BigDecimal.new('Infinity'), @fourth_range.num_range
assert_equal BigDecimal.new("0.1")..BigDecimal.new("0.2"), @first_range.num_range
assert_equal BigDecimal.new("0.1")...BigDecimal.new("0.2"), @second_range.num_range
assert_equal BigDecimal.new("0.1")...BigDecimal.new("Infinity"), @third_range.num_range
assert_equal BigDecimal.new("-Infinity")...BigDecimal.new("Infinity"), @fourth_range.num_range
assert_nil @empty_range.num_range
end
@ -148,8 +148,8 @@ def test_tsrange_values
end
def test_tstzrange_values
assert_equal Time.parse('2010-01-01 09:30:00 UTC')..Time.parse('2011-01-01 17:30:00 UTC'), @first_range.tstz_range
assert_equal Time.parse('2010-01-01 09:30:00 UTC')...Time.parse('2011-01-01 17:30:00 UTC'), @second_range.tstz_range
assert_equal Time.parse("2010-01-01 09:30:00 UTC")..Time.parse("2011-01-01 17:30:00 UTC"), @first_range.tstz_range
assert_equal Time.parse("2010-01-01 09:30:00 UTC")...Time.parse("2011-01-01 17:30:00 UTC"), @second_range.tstz_range
assert_equal(-Float::INFINITY...Float::INFINITY, @fourth_range.tstz_range)
assert_nil @empty_range.tstz_range
end
@ -183,17 +183,17 @@ def test_timezone_awareness_tzrange
end
def test_create_tstzrange
tstzrange = Time.parse('2010-01-01 14:30:00 +0100')...Time.parse('2011-02-02 14:30:00 CDT')
tstzrange = Time.parse("2010-01-01 14:30:00 +0100")...Time.parse("2011-02-02 14:30:00 CDT")
round_trip(@new_range, :tstz_range, tstzrange)
assert_equal @new_range.tstz_range, tstzrange
assert_equal @new_range.tstz_range, Time.parse('2010-01-01 13:30:00 UTC')...Time.parse('2011-02-02 19:30:00 UTC')
assert_equal @new_range.tstz_range, Time.parse("2010-01-01 13:30:00 UTC")...Time.parse("2011-02-02 19:30:00 UTC")
end
def test_update_tstzrange
assert_equal_round_trip(@first_range, :tstz_range,
Time.parse('2010-01-01 14:30:00 CDT')...Time.parse('2011-02-02 14:30:00 CET'))
Time.parse("2010-01-01 14:30:00 CDT")...Time.parse("2011-02-02 14:30:00 CET"))
assert_nil_round_trip(@first_range, :tstz_range,
Time.parse('2010-01-01 14:30:00 +0100')...Time.parse('2010-01-01 13:30:00 +0000'))
Time.parse("2010-01-01 14:30:00 +0100")...Time.parse("2010-01-01 13:30:00 +0000"))
end
def test_create_tsrange
@ -232,14 +232,14 @@ def test_timezone_awareness_tsrange
def test_create_numrange
assert_equal_round_trip(@new_range, :num_range,
BigDecimal.new('0.5')...BigDecimal.new('1'))
BigDecimal.new("0.5")...BigDecimal.new("1"))
end
def test_update_numrange
assert_equal_round_trip(@first_range, :num_range,
BigDecimal.new('0.5')...BigDecimal.new('1'))
BigDecimal.new("0.5")...BigDecimal.new("1"))
assert_nil_round_trip(@first_range, :num_range,
BigDecimal.new('0.5')...BigDecimal.new('0.5'))
BigDecimal.new("0.5")...BigDecimal.new("0.5"))
end
def test_create_daterange

@ -1,5 +1,5 @@
require 'cases/helper'
require 'support/connection_helper'
require "cases/helper"
require "support/connection_helper"
class PostgreSQLReferentialIntegrityTest < ActiveRecord::PostgreSQLTestCase
self.use_transactional_tests = false
@ -14,7 +14,7 @@ module MissingSuperuserPrivileges
def execute(sql)
if IS_REFERENTIAL_INTEGRITY_SQL.call(sql)
super "BROKEN;" rescue nil # put transaction in broken state
raise ActiveRecord::StatementInvalid, 'PG::InsufficientPrivilege'
raise ActiveRecord::StatementInvalid, "PG::InsufficientPrivilege"
else
super
end
@ -24,7 +24,7 @@ def execute(sql)
module ProgrammerMistake
def execute(sql)
if IS_REFERENTIAL_INTEGRITY_SQL.call(sql)
raise ArgumentError, 'something is not right.'
raise ArgumentError, "something is not right."
else
super
end
@ -48,10 +48,10 @@ def test_should_reraise_invalid_foreign_key_exception_and_show_warning
warning = capture(:stderr) do
e = assert_raises(ActiveRecord::InvalidForeignKey) do
@connection.disable_referential_integrity do
raise ActiveRecord::InvalidForeignKey, 'Should be re-raised'
raise ActiveRecord::InvalidForeignKey, "Should be re-raised"
end
end
assert_equal 'Should be re-raised', e.message
assert_equal "Should be re-raised", e.message
end
assert_match (/WARNING: Rails was not able to disable referential integrity/), warning
assert_match (/cause: PG::InsufficientPrivilege/), warning
@ -63,10 +63,10 @@ def test_does_not_print_warning_if_no_invalid_foreign_key_exception_was_raised
warning = capture(:stderr) do
e = assert_raises(ActiveRecord::StatementInvalid) do
@connection.disable_referential_integrity do
raise ActiveRecord::StatementInvalid, 'Should be re-raised'
raise ActiveRecord::StatementInvalid, "Should be re-raised"
end
end
assert_equal 'Should be re-raised', e.message
assert_equal "Should be re-raised", e.message
end
assert warning.blank?, "expected no warnings but got:\n#{warning}"
end

@ -6,12 +6,12 @@ class SchemaThing < ActiveRecord::Base
class SchemaAuthorizationTest < ActiveRecord::PostgreSQLTestCase
self.use_transactional_tests = false
TABLE_NAME = 'schema_things'
TABLE_NAME = "schema_things"
COLUMNS = [
'id serial primary key',
'name character varying(50)'
"id serial primary key",
"name character varying(50)"
]
USERS = ['rails_pg_schema_user1', 'rails_pg_schema_user2']
USERS = ["rails_pg_schema_user1", "rails_pg_schema_user2"]
def setup
@connection = ActiveRecord::Base.connection
@ -45,7 +45,7 @@ def test_schema_invisible
def test_session_auth=
assert_raise(ActiveRecord::StatementInvalid) do
@connection.session_auth = 'DEFAULT'
@connection.session_auth = "DEFAULT"
@connection.execute "SELECT * FROM #{TABLE_NAME}"
end
end
@ -68,7 +68,7 @@ def test_auth_with_bind
USERS.each do |u|
@connection.clear_cache!
set_session_auth u
assert_equal u, @connection.select_value("SELECT name FROM #{TABLE_NAME} WHERE id = $1", 'SQL', [bind_param(1)])
assert_equal u, @connection.select_value("SELECT name FROM #{TABLE_NAME} WHERE id = $1", "SQL", [bind_param(1)])
set_session_auth
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
@ -110,7 +110,7 @@ def test_tables_in_current_schemas
private
def set_session_auth auth = nil
@connection.session_auth = auth || 'default'
@connection.session_auth = auth || "default"
end
def bind_param(value)

@ -1,6 +1,6 @@
require "cases/helper"
require 'models/default'
require 'support/schema_dumping_helper'
require "models/default"
require "support/schema_dumping_helper"
module PGSchemaHelper
def with_schema_search_path(schema_search_path)
@ -17,32 +17,32 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase
include PGSchemaHelper
self.use_transactional_tests = false
SCHEMA_NAME = 'test_schema'
SCHEMA2_NAME = 'test_schema2'
TABLE_NAME = 'things'
CAPITALIZED_TABLE_NAME = 'Things'
INDEX_A_NAME = 'a_index_things_on_name'
INDEX_B_NAME = 'b_index_things_on_different_columns_in_each_schema'
INDEX_C_NAME = 'c_index_full_text_search'
INDEX_D_NAME = 'd_index_things_on_description_desc'
INDEX_E_NAME = 'e_index_things_on_name_vector'
INDEX_A_COLUMN = 'name'
INDEX_B_COLUMN_S1 = 'email'
INDEX_B_COLUMN_S2 = 'moment'
SCHEMA_NAME = "test_schema"
SCHEMA2_NAME = "test_schema2"
TABLE_NAME = "things"
CAPITALIZED_TABLE_NAME = "Things"
INDEX_A_NAME = "a_index_things_on_name"
INDEX_B_NAME = "b_index_things_on_different_columns_in_each_schema"
INDEX_C_NAME = "c_index_full_text_search"
INDEX_D_NAME = "d_index_things_on_description_desc"
INDEX_E_NAME = "e_index_things_on_name_vector"
INDEX_A_COLUMN = "name"
INDEX_B_COLUMN_S1 = "email"
INDEX_B_COLUMN_S2 = "moment"
INDEX_C_COLUMN = %q{(to_tsvector('english', coalesce(things.name, '')))}
INDEX_D_COLUMN = 'description'
INDEX_E_COLUMN = 'name_vector'
INDEX_D_COLUMN = "description"
INDEX_E_COLUMN = "name_vector"
COLUMNS = [
'id integer',
'name character varying(50)',
'email character varying(50)',
'description character varying(100)',
'name_vector tsvector',
'moment timestamp without time zone default now()'
"id integer",
"name character varying(50)",
"email character varying(50)",
"description character varying(100)",
"name_vector tsvector",
"moment timestamp without time zone default now()"
]
PK_TABLE_NAME = 'table_with_pk'
UNMATCHED_SEQUENCE_NAME = 'unmatched_primary_key_default_value_seq'
UNMATCHED_PK_TABLE_NAME = 'table_with_unmatched_sequence_for_pk'
PK_TABLE_NAME = "table_with_pk"
UNMATCHED_SEQUENCE_NAME = "unmatched_primary_key_default_value_seq"
UNMATCHED_PK_TABLE_NAME = "table_with_unmatched_sequence_for_pk"
class Thing1 < ActiveRecord::Base
self.table_name = "test_schema.things"
@ -61,7 +61,7 @@ class Thing4 < ActiveRecord::Base
end
class Thing5 < ActiveRecord::Base
self.table_name = 'things'
self.table_name = "things"
end
class Song < ActiveRecord::Base
@ -168,21 +168,21 @@ def test_drop_schema_with_nonexisting_schema
def test_raise_wrapped_exception_on_bad_prepare
assert_raises(ActiveRecord::StatementInvalid) do
@connection.exec_query "select * from developers where id = ?", 'sql', [bind_param(1)]
@connection.exec_query "select * from developers where id = ?", "sql", [bind_param(1)]
end
end
if ActiveRecord::Base.connection.prepared_statements
def test_schema_change_with_prepared_stmt
altered = false
@connection.exec_query "select * from developers where id = $1", 'sql', [bind_param(1)]
@connection.exec_query "alter table developers add column zomg int", 'sql', []
@connection.exec_query "select * from developers where id = $1", "sql", [bind_param(1)]
@connection.exec_query "alter table developers add column zomg int", "sql", []
altered = true
@connection.exec_query "select * from developers where id = $1", 'sql', [bind_param(1)]
@connection.exec_query "select * from developers where id = $1", "sql", [bind_param(1)]
ensure
# We are not using DROP COLUMN IF EXISTS because that syntax is only
# supported by pg 9.X
@connection.exec_query("alter table developers drop column zomg", 'sql', []) if altered
@connection.exec_query("alter table developers drop column zomg", "sql", []) if altered
end
end
@ -200,7 +200,7 @@ def test_data_source_exists_when_on_schema_search_path
end
def test_data_source_exists_when_not_on_schema_search_path
with_schema_search_path('PUBLIC') do
with_schema_search_path("PUBLIC") do
assert(!@connection.data_source_exists?(TABLE_NAME), "data_source exists but should not be found")
end
end
@ -246,9 +246,9 @@ def test_with_schema_search_path
end
def test_proper_encoding_of_table_name
assert_equal '"table_name"', @connection.quote_table_name('table_name')
assert_equal '"table_name"', @connection.quote_table_name("table_name")
assert_equal '"table.name"', @connection.quote_table_name('"table.name"')
assert_equal '"schema_name"."table_name"', @connection.quote_table_name('schema_name.table_name')
assert_equal '"schema_name"."table_name"', @connection.quote_table_name("schema_name.table_name")
assert_equal '"schema_name"."table.name"', @connection.quote_table_name('schema_name."table.name"')
assert_equal '"schema.name"."table_name"', @connection.quote_table_name('"schema.name".table_name')
assert_equal '"schema.name"."table.name"', @connection.quote_table_name('"schema.name"."table.name"')
@ -287,7 +287,7 @@ def test_classes_with_qualified_schema_name
def test_raise_on_unquoted_schema_name
assert_raises(ActiveRecord::StatementInvalid) do
with_schema_search_path '$user,public'
with_schema_search_path "$user,public"
end
end
@ -307,7 +307,7 @@ def test_index_name_exists
assert @connection.index_name_exists?(TABLE_NAME, INDEX_D_NAME, true)
assert @connection.index_name_exists?(TABLE_NAME, INDEX_E_NAME, true)
assert @connection.index_name_exists?(TABLE_NAME, INDEX_E_NAME, true)
assert_not @connection.index_name_exists?(TABLE_NAME, 'missing_index', true)
assert_not @connection.index_name_exists?(TABLE_NAME, "missing_index", true)
end
end
@ -356,13 +356,13 @@ def test_primary_key_with_schema_specified
%(#{SCHEMA_NAME}."#{PK_TABLE_NAME}"),
%(#{SCHEMA_NAME}.#{PK_TABLE_NAME})
].each do |given|
assert_equal 'id', @connection.primary_key(given), "primary key should be found when table referenced as #{given}"
assert_equal "id", @connection.primary_key(given), "primary key should be found when table referenced as #{given}"
end
end
def test_primary_key_assuming_schema_search_path
with_schema_search_path(SCHEMA_NAME) do
assert_equal 'id', @connection.primary_key(PK_TABLE_NAME), "primary key should be found"
assert_equal "id", @connection.primary_key(PK_TABLE_NAME), "primary key should be found"
end
end
@ -381,7 +381,7 @@ def test_pk_and_sequence_for_with_schema_specified
%("#{SCHEMA_NAME}"."#{UNMATCHED_PK_TABLE_NAME}")
].each do |given|
pk, seq = @connection.pk_and_sequence_for(given)
assert_equal 'id', pk, "primary key should be found when table referenced as #{given}"
assert_equal "id", pk, "primary key should be found when table referenced as #{given}"
assert_equal pg_name.new(SCHEMA_NAME, "#{PK_TABLE_NAME}_id_seq"), seq, "sequence name should be found when table referenced as #{given}" if given == %("#{SCHEMA_NAME}"."#{PK_TABLE_NAME}")
assert_equal pg_name.new(SCHEMA_NAME, UNMATCHED_SEQUENCE_NAME), seq, "sequence name should be found when table referenced as #{given}" if given == %("#{SCHEMA_NAME}"."#{UNMATCHED_PK_TABLE_NAME}")
end
@ -389,10 +389,10 @@ def test_pk_and_sequence_for_with_schema_specified
def test_current_schema
{
%('$user',public) => 'public',
%('$user',public) => "public",
SCHEMA_NAME => SCHEMA_NAME,
%(#{SCHEMA2_NAME},#{SCHEMA_NAME},public) => SCHEMA2_NAME,
%(public,#{SCHEMA2_NAME},#{SCHEMA_NAME}) => 'public'
%(public,#{SCHEMA2_NAME},#{SCHEMA_NAME}) => "public"
}.each do |given,expect|
with_schema_search_path(given) { assert_equal expect, @connection.current_schema }
end
@ -414,10 +414,10 @@ def test_prepared_statements_with_multiple_schemas
def test_schema_exists?
{
'public' => true,
"public" => true,
SCHEMA_NAME => true,
SCHEMA2_NAME => true,
'darkside' => false
"darkside" => false
}.each do |given,expect|
assert_equal expect, @connection.schema_exists?(given)
end
@ -442,7 +442,7 @@ def test_set_pk_sequence
private
def columns(table_name)
@connection.send(:column_definitions, table_name).map do |name, type, default|
"#{name} #{type}" + (default ? " default #{default}" : '')
"#{name} #{type}" + (default ? " default #{default}" : "")
end
end

@ -1,5 +1,5 @@
require "cases/helper"
require 'support/schema_dumping_helper'
require "support/schema_dumping_helper"
class PostgresqlSerialTest < ActiveRecord::PostgreSQLTestCase
include SchemaDumpingHelper

@ -1,4 +1,4 @@
require 'cases/helper'
require "cases/helper"
module ActiveRecord
module ConnectionAdapters
@ -17,22 +17,22 @@ class StatementPoolTest < ActiveRecord::PostgreSQLTestCase
if Process.respond_to?(:fork)
def test_cache_is_per_pid
cache = StatementPool.new nil, 10
cache['foo'] = 'bar'
assert_equal 'bar', cache['foo']
cache["foo"] = "bar"
assert_equal "bar", cache["foo"]
pid = fork {
lookup = cache['foo'];
lookup = cache["foo"];
exit!(!lookup)
}
Process.waitpid pid
assert $?.success?, 'process should exit successfully'
assert $?.success?, "process should exit successfully"
end
end
def test_dealloc_does_not_raise_on_inactive_connection
cache = StatementPool.new InactivePGconn.new, 10
cache['foo'] = 'bar'
cache["foo"] = "bar"
assert_nothing_raised { cache.clear }
end
end

@ -1,6 +1,6 @@
require 'cases/helper'
require 'models/developer'
require 'models/topic'
require "cases/helper"
require "models/developer"
require "models/topic"
class PostgresqlTimestampTest < ActiveRecord::PostgreSQLTestCase
class PostgresqlTimestampWithZone < ActiveRecord::Base; end
@ -32,7 +32,7 @@ def test_timestamp_with_zone_values_without_rails_time_zone_support
with_timezone_config default: :local, aware_attributes: false do
@connection.reconnect!
# make sure to use a non-UTC time zone
@connection.execute("SET time zone 'America/Jamaica'", 'SCHEMA')
@connection.execute("SET time zone 'America/Jamaica'", "SCHEMA")
timestamp = PostgresqlTimestampWithZone.find(1)
assert_equal Time.utc(2010,1,1, 11,0,0), timestamp.time
@ -54,19 +54,19 @@ def test_group_by_date
def test_load_infinity_and_beyond
d = Developer.find_by_sql("select 'infinity'::timestamp as updated_at")
assert d.first.updated_at.infinite?, 'timestamp should be infinite'
assert d.first.updated_at.infinite?, "timestamp should be infinite"
d = Developer.find_by_sql("select '-infinity'::timestamp as updated_at")
time = d.first.updated_at
assert time.infinite?, 'timestamp should be infinite'
assert time.infinite?, "timestamp should be infinite"
assert_operator time, :<, 0
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

@ -1,21 +1,21 @@
require "cases/helper"
require 'support/connection_helper'
require "support/connection_helper"
module ActiveRecord
class PostgresqlTransactionTest < ActiveRecord::PostgreSQLTestCase
self.use_transactional_tests = false
class Sample < ActiveRecord::Base
self.table_name = 'samples'
self.table_name = "samples"
end
setup do
@connection = ActiveRecord::Base.connection
@connection.transaction do
@connection.drop_table 'samples', if_exists: true
@connection.create_table('samples') do |t|
t.integer 'value'
@connection.drop_table "samples", if_exists: true
@connection.create_table("samples") do |t|
t.integer "value"
end
end
@ -23,7 +23,7 @@ class Sample < ActiveRecord::Base
end
teardown do
@connection.drop_table 'samples', if_exists: true
@connection.drop_table "samples", if_exists: true
end
test "raises SerializationFailure when a serialization failure occurs" do
@ -89,7 +89,7 @@ class Sample < ActiveRecord::Base
def with_warning_suppression
log_level = @connection.client_min_messages
@connection.client_min_messages = 'error'
@connection.client_min_messages = "error"
yield
@connection.client_min_messages = log_level
end

@ -1,4 +1,4 @@
require 'cases/helper'
require "cases/helper"
class PostgresqlTypeLookupTest < ActiveRecord::PostgreSQLTestCase
setup do
@ -9,8 +9,8 @@ class PostgresqlTypeLookupTest < ActiveRecord::PostgreSQLTestCase
box_array = @connection.type_map.lookup(1020)
int_array = @connection.type_map.lookup(1007)
assert_equal ';', box_array.delimiter
assert_equal ',', int_array.delimiter
assert_equal ";", box_array.delimiter
assert_equal ",", int_array.delimiter
end
test "array types correctly respect registration of subtypes" do

@ -1,5 +1,5 @@
require 'cases/helper'
require 'active_record/connection_adapters/postgresql/utils'
require "cases/helper"
require "active_record/connection_adapters/postgresql/utils"
class PostgreSQLUtilsTest < ActiveRecord::PostgreSQLTestCase
Name = ActiveRecord::ConnectionAdapters::PostgreSQL::Name
@ -7,14 +7,14 @@ class PostgreSQLUtilsTest < ActiveRecord::PostgreSQLTestCase
def test_extract_schema_qualified_name
{
%(table_name) => [nil,'table_name'],
%("table.name") => [nil,'table.name'],
%(table_name) => [nil,"table_name"],
%("table.name") => [nil,"table.name"],
%(schema.table_name) => %w{schema table_name},
%("schema".table_name) => %w{schema table_name},
%(schema."table_name") => %w{schema table_name},
%("schema"."table_name") => %w{schema table_name},
%("even spaces".table) => ['even spaces','table'],
%(schema."table.name") => ['schema', 'table.name']
%("even spaces".table) => ["even spaces","table"],
%(schema."table.name") => ["schema", "table.name"]
}.each do |given, expect|
assert_equal Name.new(*expect), extract_schema_qualified_name(given)
end

@ -1,5 +1,5 @@
require "cases/helper"
require 'support/schema_dumping_helper'
require "support/schema_dumping_helper"
module PostgresqlUUIDHelper
def connection
@ -20,10 +20,10 @@ class UUIDType < ActiveRecord::Base
end
setup do
enable_extension!('uuid-ossp', connection)
enable_extension!("uuid-ossp", connection)
connection.create_table "uuid_data_type" do |t|
t.uuid 'guid'
t.uuid "guid"
end
end
@ -34,13 +34,13 @@ class UUIDType < ActiveRecord::Base
def test_change_column_default
@connection.add_column :uuid_data_type, :thingy, :uuid, null: false, default: "uuid_generate_v1()"
UUIDType.reset_column_information
column = UUIDType.columns_hash['thingy']
column = UUIDType.columns_hash["thingy"]
assert_equal "uuid_generate_v1()", column.default_function
@connection.change_column :uuid_data_type, :thingy, :uuid, null: false, default: "uuid_generate_v4()"
UUIDType.reset_column_information
column = UUIDType.columns_hash['thingy']
column = UUIDType.columns_hash["thingy"]
assert_equal "uuid_generate_v4()", column.default_function
ensure
UUIDType.reset_column_information
@ -57,46 +57,46 @@ def test_data_type_of_uuid_types
end
def test_treat_blank_uuid_as_nil
UUIDType.create! guid: ''
UUIDType.create! guid: ""
assert_equal(nil, UUIDType.last.guid)
end
def test_treat_invalid_uuid_as_nil
uuid = UUIDType.create! guid: 'foobar'
uuid = UUIDType.create! guid: "foobar"
assert_equal(nil, uuid.guid)
end
def test_invalid_uuid_dont_modify_before_type_cast
uuid = UUIDType.new guid: 'foobar'
assert_equal 'foobar', uuid.guid_before_type_cast
uuid = UUIDType.new guid: "foobar"
assert_equal "foobar", uuid.guid_before_type_cast
end
def test_acceptable_uuid_regex
# Valid uuids
['A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11',
'{a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11}',
'a0eebc999c0b4ef8bb6d6bb9bd380a11',
'a0ee-bc99-9c0b-4ef8-bb6d-6bb9-bd38-0a11',
'{a0eebc99-9c0b4ef8-bb6d6bb9-bd380a11}',
["A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11",
"{a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11}",
"a0eebc999c0b4ef8bb6d6bb9bd380a11",
"a0ee-bc99-9c0b-4ef8-bb6d-6bb9-bd38-0a11",
"{a0eebc99-9c0b4ef8-bb6d6bb9-bd380a11}",
# The following is not a valid RFC 4122 UUID, but PG doesn't seem to care,
# so we shouldn't block it either. (Pay attention to "fb6d" the "f" here
# is invalid it must be one of 8, 9, A, B, a, b according to the spec.)
'{a0eebc99-9c0b-4ef8-fb6d-6bb9bd380a11}',
"{a0eebc99-9c0b-4ef8-fb6d-6bb9bd380a11}",
].each do |valid_uuid|
uuid = UUIDType.new guid: valid_uuid
assert_not_nil uuid.guid
end
# Invalid uuids
[['A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11'],
[["A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11"],
Hash.new,
0,
0.0,
true,
'Z0000C99-9C0B-4EF8-BB6D-6BB9BD380A11',
'a0eebc999r0b4ef8ab6d6bb9bd380a11',
'a0ee-bc99------4ef8-bb6d-6bb9-bd38-0a11',
'{a0eebc99-bb6d6bb9-bd380a11}'].each do |invalid_uuid|
"Z0000C99-9C0B-4EF8-BB6D-6BB9BD380A11",
"a0eebc999r0b4ef8ab6d6bb9bd380a11",
"a0ee-bc99------4ef8-bb6d-6bb9-bd38-0a11",
"{a0eebc99-bb6d6bb9-bd380a11}"].each do |invalid_uuid|
uuid = UUIDType.new guid: invalid_uuid
assert_nil uuid.guid
end
@ -142,13 +142,13 @@ class PostgresqlUUIDGenerationTest < ActiveRecord::PostgreSQLTestCase
include SchemaDumpingHelper
class UUID < ActiveRecord::Base
self.table_name = 'pg_uuids'
self.table_name = "pg_uuids"
end
setup do
connection.create_table('pg_uuids', id: :uuid, default: 'uuid_generate_v1()') do |t|
t.string 'name'
t.uuid 'other_uuid', default: 'uuid_generate_v4()'
connection.create_table("pg_uuids", id: :uuid, default: "uuid_generate_v1()") do |t|
t.string "name"
t.uuid "other_uuid", default: "uuid_generate_v4()"
end
# Create custom PostgreSQL function to generate UUIDs
@ -160,21 +160,21 @@ class UUID < ActiveRecord::Base
SQL
# Create such a table with custom function as default value generator
connection.create_table('pg_uuids_2', id: :uuid, default: 'my_uuid_generator()') do |t|
t.string 'name'
t.uuid 'other_uuid_2', default: 'my_uuid_generator()'
connection.create_table("pg_uuids_2", id: :uuid, default: "my_uuid_generator()") do |t|
t.string "name"
t.uuid "other_uuid_2", default: "my_uuid_generator()"
end
end
teardown do
drop_table "pg_uuids"
drop_table 'pg_uuids_2'
connection.execute 'DROP FUNCTION IF EXISTS my_uuid_generator();'
drop_table "pg_uuids_2"
connection.execute "DROP FUNCTION IF EXISTS my_uuid_generator();"
end
if ActiveRecord::Base.connection.supports_extensions?
def test_id_is_uuid
assert_equal :uuid, UUID.columns_hash['id'].type
assert_equal :uuid, UUID.columns_hash["id"].type
assert UUID.primary_key
end
@ -190,8 +190,8 @@ def test_auto_create_uuid
end
def test_pk_and_sequence_for_uuid_primary_key
pk, seq = connection.pk_and_sequence_for('pg_uuids')
assert_equal 'id', pk
pk, seq = connection.pk_and_sequence_for("pg_uuids")
assert_equal "id", pk
assert_equal nil, seq
end
@ -214,9 +214,9 @@ class PostgresqlUUIDTestNilDefault < ActiveRecord::PostgreSQLTestCase
include SchemaDumpingHelper
setup do
connection.create_table('pg_uuids', id: false) do |t|
connection.create_table("pg_uuids", id: false) do |t|
t.primary_key :id, :uuid, default: nil
t.string 'name'
t.string "name"
end
end
@ -244,23 +244,23 @@ class PostgresqlUUIDTestInverseOf < ActiveRecord::PostgreSQLTestCase
include PostgresqlUUIDHelper
class UuidPost < ActiveRecord::Base
self.table_name = 'pg_uuid_posts'
self.table_name = "pg_uuid_posts"
has_many :uuid_comments, inverse_of: :uuid_post
end
class UuidComment < ActiveRecord::Base
self.table_name = 'pg_uuid_comments'
self.table_name = "pg_uuid_comments"
belongs_to :uuid_post
end
setup do
connection.transaction do
connection.create_table('pg_uuid_posts', id: :uuid) do |t|
t.string 'title'
connection.create_table("pg_uuid_posts", id: :uuid) do |t|
t.string "title"
end
connection.create_table('pg_uuid_comments', id: :uuid) do |t|
connection.create_table("pg_uuid_comments", id: :uuid) do |t|
t.references :uuid_post, type: :uuid
t.string 'content'
t.string "content"
end
end
end

@ -1,28 +1,28 @@
require 'cases/helper'
require 'support/schema_dumping_helper'
require "cases/helper"
require "support/schema_dumping_helper"
class PostgresqlXMLTest < ActiveRecord::PostgreSQLTestCase
include SchemaDumpingHelper
class XmlDataType < ActiveRecord::Base
self.table_name = 'xml_data_type'
self.table_name = "xml_data_type"
end
def setup
@connection = ActiveRecord::Base.connection
begin
@connection.transaction do
@connection.create_table('xml_data_type') do |t|
t.xml 'payload'
@connection.create_table("xml_data_type") do |t|
t.xml "payload"
end
end
rescue ActiveRecord::StatementInvalid
skip "do not test on PG without xml"
end
@column = XmlDataType.columns_hash['payload']
@column = XmlDataType.columns_hash["payload"]
end
teardown do
@connection.drop_table 'xml_data_type', if_exists: true
@connection.drop_table "xml_data_type", if_exists: true
end
def test_column

@ -1,5 +1,5 @@
require "cases/helper"
require 'support/schema_dumping_helper'
require "support/schema_dumping_helper"
class SQLite3CollationTest < ActiveRecord::SQLite3TestCase
include SchemaDumpingHelper
@ -7,8 +7,8 @@ class SQLite3CollationTest < ActiveRecord::SQLite3TestCase
def setup
@connection = ActiveRecord::Base.connection
@connection.create_table :collation_table_sqlite3, force: true do |t|
t.string :string_nocase, collation: 'NOCASE'
t.text :text_rtrim, collation: 'RTRIM'
t.string :string_nocase, collation: "NOCASE"
t.text :text_rtrim, collation: "RTRIM"
end
end
@ -17,32 +17,32 @@ def teardown
end
test "string column with collation" do
column = @connection.columns(:collation_table_sqlite3).find { |c| c.name == 'string_nocase' }
column = @connection.columns(:collation_table_sqlite3).find { |c| c.name == "string_nocase" }
assert_equal :string, column.type
assert_equal 'NOCASE', column.collation
assert_equal "NOCASE", column.collation
end
test "text column with collation" do
column = @connection.columns(:collation_table_sqlite3).find { |c| c.name == 'text_rtrim' }
column = @connection.columns(:collation_table_sqlite3).find { |c| c.name == "text_rtrim" }
assert_equal :text, column.type
assert_equal 'RTRIM', column.collation
assert_equal "RTRIM", column.collation
end
test "add column with collation" do
@connection.add_column :collation_table_sqlite3, :title, :string, collation: 'RTRIM'
@connection.add_column :collation_table_sqlite3, :title, :string, collation: "RTRIM"
column = @connection.columns(:collation_table_sqlite3).find { |c| c.name == 'title' }
column = @connection.columns(:collation_table_sqlite3).find { |c| c.name == "title" }
assert_equal :string, column.type
assert_equal 'RTRIM', column.collation
assert_equal "RTRIM", column.collation
end
test "change column with collation" do
@connection.add_column :collation_table_sqlite3, :description, :string
@connection.change_column :collation_table_sqlite3, :description, :text, collation: 'RTRIM'
@connection.change_column :collation_table_sqlite3, :description, :text, collation: "RTRIM"
column = @connection.columns(:collation_table_sqlite3).find { |c| c.name == 'description' }
column = @connection.columns(:collation_table_sqlite3).find { |c| c.name == "description" }
assert_equal :text, column.type
assert_equal 'RTRIM', column.collation
assert_equal "RTRIM", column.collation
end
test "schema dump includes collation" do

@ -10,7 +10,7 @@ class << @connection
end
end
def test_copy_table(from = 'customers', to = 'customers2', options = {})
def test_copy_table(from = "customers", to = "customers2", options = {})
assert_nothing_raised {copy_table(from, to, options)}
assert_equal row_count(from), row_count(to)
@ -24,39 +24,39 @@ def test_copy_table(from = 'customers', to = 'customers2', options = {})
end
def test_copy_table_renaming_column
test_copy_table('customers', 'customers2',
:rename => {'name' => 'person_name'}) do |from, to, options|
expected = column_values(from, 'name')
assert_equal expected, column_values(to, 'person_name')
test_copy_table("customers", "customers2",
: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}"
end
end
def test_copy_table_allows_to_pass_options_to_create_table
@connection.create_table('blocker_table')
test_copy_table('customers', 'blocker_table', force: true)
@connection.create_table("blocker_table")
test_copy_table("customers", "blocker_table", force: true)
end
def test_copy_table_with_index
test_copy_table('comments', 'comments_with_index') do
@connection.add_index('comments_with_index', ['post_id', 'type'])
test_copy_table('comments_with_index', 'comments_with_index2') do
assert_equal table_indexes_without_name('comments_with_index'),
table_indexes_without_name('comments_with_index2')
test_copy_table("comments", "comments_with_index") do
@connection.add_index("comments_with_index", ["post_id", "type"])
test_copy_table("comments_with_index", "comments_with_index2") do
assert_equal table_indexes_without_name("comments_with_index"),
table_indexes_without_name("comments_with_index2")
end
end
end
def test_copy_table_without_primary_key
test_copy_table('developers_projects', 'programmers_projects') do
assert_nil @connection.primary_key('programmers_projects')
test_copy_table("developers_projects", "programmers_projects") do
assert_nil @connection.primary_key("programmers_projects")
end
end
def test_copy_table_with_id_col_that_is_not_primary_key
test_copy_table('goofy_string_id', 'goofy_string_id2') do
original_id = @connection.columns('goofy_string_id').detect{|col| col.name == 'id' }
copied_id = @connection.columns('goofy_string_id2').detect{|col| col.name == 'id' }
test_copy_table("goofy_string_id", "goofy_string_id2") do
original_id = @connection.columns("goofy_string_id").detect{|col| col.name == "id" }
copied_id = @connection.columns("goofy_string_id2").detect{|col| col.name == "id" }
assert_equal original_id.type, copied_id.type
assert_equal original_id.sql_type, copied_id.sql_type
assert_equal original_id.limit, copied_id.limit
@ -64,15 +64,15 @@ def test_copy_table_with_id_col_that_is_not_primary_key
end
def test_copy_table_with_unconventional_primary_key
test_copy_table('owners', 'owners_unconventional') do
original_pk = @connection.primary_key('owners')
copied_pk = @connection.primary_key('owners_unconventional')
test_copy_table("owners", "owners_unconventional") do
original_pk = @connection.primary_key("owners")
copied_pk = @connection.primary_key("owners_unconventional")
assert_equal original_pk, copied_pk
end
end
def test_copy_table_with_binary_column
test_copy_table 'binaries', 'binaries2'
test_copy_table "binaries", "binaries2"
end
protected
@ -81,7 +81,7 @@ def copy_table(from, to, options = {})
end
def column_names(table)
@connection.table_structure(table).map {|column| column['name']}
@connection.table_structure(table).map {|column| column["name"]}
end
def column_values(table, column)
@ -93,6 +93,6 @@ def table_indexes_without_name(table)
end
def row_count(table)
@connection.select_one("SELECT COUNT(*) AS count FROM #{table}")['count']
@connection.select_one("SELECT COUNT(*) AS count FROM #{table}")["count"]
end
end

@ -1,6 +1,6 @@
require "cases/helper"
require 'models/developer'
require 'models/computer'
require "models/developer"
require "models/computer"
class SQLite3ExplainTest < ActiveRecord::SQLite3TestCase
fixtures :developers

@ -1,7 +1,7 @@
require "cases/helper"
require 'bigdecimal'
require 'yaml'
require 'securerandom'
require "bigdecimal"
require "yaml"
require "securerandom"
class SQLite3QuotingTest < ActiveRecord::SQLite3TestCase
def setup
@ -16,7 +16,7 @@ def test_type_cast_binary_encoding_without_logger
end
def test_type_cast_symbol
assert_equal 'foo', @conn.type_cast(:foo)
assert_equal "foo", @conn.type_cast(:foo)
end
def test_type_cast_date
@ -41,15 +41,15 @@ def test_type_cast_nil
end
def test_type_cast_true
assert_equal 't', @conn.type_cast(true)
assert_equal "t", @conn.type_cast(true)
end
def test_type_cast_false
assert_equal 'f', @conn.type_cast(false)
assert_equal "f", @conn.type_cast(false)
end
def test_type_cast_bigdecimal
bd = BigDecimal.new '10.0'
bd = BigDecimal.new "10.0"
assert_equal bd.to_f, @conn.type_cast(bd)
end
@ -79,7 +79,7 @@ def quoted_id
end
def test_quoting_binary_strings
value = "hello".encode('ascii-8bit')
value = "hello".encode("ascii-8bit")
type = ActiveRecord::Type::String.new
assert_equal "'hello'", @conn.quote(type.serialize(value))

@ -1,7 +1,7 @@
require "cases/helper"
require 'models/owner'
require 'tempfile'
require 'support/ddl_helper'
require "models/owner"
require "tempfile"
require "support/ddl_helper"
module ActiveRecord
module ConnectionAdapters
@ -14,22 +14,22 @@ class DualEncoding < ActiveRecord::Base
end
def setup
@conn = Base.sqlite3_connection database: ':memory:',
adapter: 'sqlite3',
@conn = Base.sqlite3_connection database: ":memory:",
adapter: "sqlite3",
timeout: 100
end
def test_bad_connection
assert_raise ActiveRecord::NoDatabaseError do
connection = ActiveRecord::Base.sqlite3_connection(adapter: "sqlite3", database: "/tmp/should/_not/_exist/-cinco-dog.db")
connection.drop_table 'ex', if_exists: true
connection.drop_table "ex", if_exists: true
end
end
unless in_memory_db?
def test_connect_with_url
original_connection = ActiveRecord::Base.remove_connection
tf = Tempfile.open 'whatever'
tf = Tempfile.open "whatever"
url = "sqlite3:#{tf.path}"
ActiveRecord::Base.establish_connection(url)
assert ActiveRecord::Base.connection
@ -51,7 +51,7 @@ def test_connect_memory_with_url
def test_valid_column
with_example_table do
column = @conn.columns('ex').find { |col| col.name == 'id' }
column = @conn.columns("ex").find { |col| col.name == "id" }
assert @conn.valid_type?(column.type)
end
end
@ -66,9 +66,9 @@ def test_invalid_column
end
def test_column_types
owner = Owner.create!(name: "hello".encode('ascii-8bit'))
owner = Owner.create!(name: "hello".encode("ascii-8bit"))
owner.reload
select = Owner.columns.map { |c| "typeof(#{c.name})" }.join ', '
select = Owner.columns.map { |c| "typeof(#{c.name})" }.join ", "
result = Owner.connection.exec_query <<-esql
SELECT #{select}
FROM #{Owner.table_name}
@ -83,10 +83,10 @@ def test_column_types
def test_exec_insert
with_example_table do
vals = [Relation::QueryAttribute.new("number", 10, Type::Value.new)]
@conn.exec_insert('insert into ex (number) VALUES (?)', 'SQL', vals)
@conn.exec_insert("insert into ex (number) VALUES (?)", "SQL", vals)
result = @conn.exec_query(
'select number from ex where number = ?', 'SQL', vals)
"select number from ex where number = ?", "SQL", vals)
assert_equal 1, result.rows.length
assert_equal 10, result.rows.first.first
@ -94,8 +94,8 @@ def test_exec_insert
end
def test_primary_key_returns_nil_for_no_pk
with_example_table 'id int, data string' do
assert_nil @conn.primary_key('ex')
with_example_table "id int, data string" do
assert_nil @conn.primary_key("ex")
end
end
@ -107,69 +107,69 @@ def test_connection_no_db
def test_bad_timeout
assert_raises(TypeError) do
Base.sqlite3_connection database: ':memory:',
adapter: 'sqlite3',
timeout: 'usa'
Base.sqlite3_connection database: ":memory:",
adapter: "sqlite3",
timeout: "usa"
end
end
# connection is OK with a nil timeout
def test_nil_timeout
conn = Base.sqlite3_connection database: ':memory:',
adapter: 'sqlite3',
conn = Base.sqlite3_connection database: ":memory:",
adapter: "sqlite3",
timeout: nil
assert conn, 'made a connection'
assert conn, "made a connection"
end
def test_connect
assert @conn, 'should have connection'
assert @conn, "should have connection"
end
# sqlite3 defaults to UTF-8 encoding
def test_encoding
assert_equal 'UTF-8', @conn.encoding
assert_equal "UTF-8", @conn.encoding
end
def test_exec_no_binds
with_example_table 'id int, data string' do
result = @conn.exec_query('SELECT id, data FROM ex')
with_example_table "id int, data string" do
result = @conn.exec_query("SELECT id, data FROM ex")
assert_equal 0, result.rows.length
assert_equal 2, result.columns.length
assert_equal %w{ id data }, result.columns
@conn.exec_query('INSERT INTO ex (id, data) VALUES (1, "foo")')
result = @conn.exec_query('SELECT id, data FROM ex')
result = @conn.exec_query("SELECT id, data FROM ex")
assert_equal 1, result.rows.length
assert_equal 2, result.columns.length
assert_equal [[1, 'foo']], result.rows
assert_equal [[1, "foo"]], result.rows
end
end
def test_exec_query_with_binds
with_example_table 'id int, data string' do
with_example_table "id int, data string" do
@conn.exec_query('INSERT INTO ex (id, data) VALUES (1, "foo")')
result = @conn.exec_query(
'SELECT id, data FROM ex WHERE id = ?', nil, [Relation::QueryAttribute.new(nil, 1, Type::Value.new)])
"SELECT id, data FROM ex WHERE id = ?", nil, [Relation::QueryAttribute.new(nil, 1, Type::Value.new)])
assert_equal 1, result.rows.length
assert_equal 2, result.columns.length
assert_equal [[1, 'foo']], result.rows
assert_equal [[1, "foo"]], result.rows
end
end
def test_exec_query_typecasts_bind_vals
with_example_table 'id int, data string' do
with_example_table "id int, data string" do
@conn.exec_query('INSERT INTO ex (id, data) VALUES (1, "foo")')
result = @conn.exec_query(
'SELECT id, data FROM ex WHERE id = ?', nil, [Relation::QueryAttribute.new("id", "1-fuu", Type::Integer.new)])
"SELECT id, data FROM ex WHERE id = ?", nil, [Relation::QueryAttribute.new("id", "1-fuu", Type::Integer.new)])
assert_equal 1, result.rows.length
assert_equal 2, result.columns.length
assert_equal [[1, 'foo']], result.rows
assert_equal [[1, "foo"]], result.rows
end
end
@ -182,15 +182,15 @@ def test_quote_binary_column_escapes_it
)
eosql
str = "\x80".force_encoding("ASCII-8BIT")
binary = DualEncoding.new name: 'いただきます!', data: str
binary = DualEncoding.new name: "いただきます!", data: str
binary.save!
assert_equal str, binary.data
ensure
DualEncoding.connection.drop_table 'dual_encodings', if_exists: true
DualEncoding.connection.drop_table "dual_encodings", if_exists: true
end
def test_type_cast_should_not_mutate_encoding
name = 'hello'.force_encoding(Encoding::ASCII_8BIT)
name = "hello".force_encoding(Encoding::ASCII_8BIT)
Owner.create(name: name)
assert_equal Encoding::ASCII_8BIT, name.encoding
ensure
@ -204,8 +204,8 @@ def test_execute
assert_equal 1, records.length
record = records.first
assert_equal 10, record['number']
assert_equal 1, record['id']
assert_equal 10, record["number"]
assert_equal 1, record["id"]
end
end
@ -226,7 +226,7 @@ def test_insert_logged
def test_insert_id_value_returned
with_example_table do
sql = "INSERT INTO ex (number) VALUES (10)"
idval = 'vuvuzela'
idval = "vuvuzela"
id = @conn.insert(sql, nil, nil, idval)
assert_equal idval, id
end
@ -237,7 +237,7 @@ def test_select_rows
2.times do |i|
@conn.create "INSERT INTO ex (number) VALUES (#{i})"
end
rows = @conn.select_rows 'select number, id from ex'
rows = @conn.select_rows "select number, id from ex"
assert_equal [[0, 1], [1, 2]], rows
end
end
@ -254,7 +254,7 @@ def test_select_rows_logged
def test_transaction
with_example_table do
count_sql = 'select count(*) from ex'
count_sql = "select count(*) from ex"
@conn.begin_db_transaction
@conn.create "INSERT INTO ex (number) VALUES (10)"
@ -268,7 +268,7 @@ def test_transaction
def test_tables
with_example_table do
ActiveSupport::Deprecation.silence { assert_equal %w{ ex }, @conn.tables }
with_example_table 'id integer PRIMARY KEY AUTOINCREMENT, number integer', 'people' do
with_example_table "id integer PRIMARY KEY AUTOINCREMENT, number integer", "people" do
ActiveSupport::Deprecation.silence { assert_equal %w{ ex people }.sort, @conn.tables.sort }
end
end
@ -279,17 +279,17 @@ def test_tables_logs_name
SELECT name FROM sqlite_master
WHERE type IN ('table','view') AND name <> 'sqlite_sequence'
SQL
assert_logged [[sql.squish, 'SCHEMA', []]] do
assert_logged [[sql.squish, "SCHEMA", []]] do
ActiveSupport::Deprecation.silence do
@conn.tables('hello')
@conn.tables("hello")
end
end
end
def test_indexes_logs_name
with_example_table do
assert_logged [["PRAGMA index_list(\"ex\")", 'SCHEMA', []]] do
@conn.indexes('ex', 'hello')
assert_logged [["PRAGMA index_list(\"ex\")", "SCHEMA", []]] do
@conn.indexes("ex", "hello")
end
end
end
@ -300,9 +300,9 @@ def test_table_exists_logs_name
SELECT name FROM sqlite_master
WHERE type IN ('table','view') AND name <> 'sqlite_sequence' AND name = 'ex'
SQL
assert_logged [[sql.squish, 'SCHEMA', []]] do
assert_logged [[sql.squish, "SCHEMA", []]] do
ActiveSupport::Deprecation.silence do
assert @conn.table_exists?('ex')
assert @conn.table_exists?("ex")
end
end
end
@ -310,7 +310,7 @@ def test_table_exists_logs_name
def test_columns
with_example_table do
columns = @conn.columns('ex').sort_by(&:name)
columns = @conn.columns("ex").sort_by(&:name)
assert_equal 2, columns.length
assert_equal %w{ id number }.sort, columns.map(&:name)
assert_equal [nil, nil], columns.map(&:default)
@ -319,17 +319,17 @@ def test_columns
end
def test_columns_with_default
with_example_table 'id integer PRIMARY KEY AUTOINCREMENT, number integer default 10' do
column = @conn.columns('ex').find { |x|
x.name == 'number'
with_example_table "id integer PRIMARY KEY AUTOINCREMENT, number integer default 10" do
column = @conn.columns("ex").find { |x|
x.name == "number"
}
assert_equal '10', column.default
assert_equal "10", column.default
end
end
def test_columns_with_not_null
with_example_table 'id integer PRIMARY KEY AUTOINCREMENT, number integer not null' do
column = @conn.columns('ex').find { |x| x.name == 'number' }
with_example_table "id integer PRIMARY KEY AUTOINCREMENT, number integer not null" do
column = @conn.columns("ex").find { |x| x.name == "number" }
assert_not column.null, "column should not be null"
end
end
@ -337,59 +337,59 @@ def test_columns_with_not_null
def test_indexes_logs
with_example_table do
assert_logged [["PRAGMA index_list(\"ex\")", "SCHEMA", []]] do
@conn.indexes('ex')
@conn.indexes("ex")
end
end
end
def test_no_indexes
assert_equal [], @conn.indexes('items')
assert_equal [], @conn.indexes("items")
end
def test_index
with_example_table do
@conn.add_index 'ex', 'id', unique: true, name: 'fun'
index = @conn.indexes('ex').find { |idx| idx.name == 'fun' }
@conn.add_index "ex", "id", unique: true, name: "fun"
index = @conn.indexes("ex").find { |idx| idx.name == "fun" }
assert_equal 'ex', index.table
assert index.unique, 'index is unique'
assert_equal ['id'], index.columns
assert_equal "ex", index.table
assert index.unique, "index is unique"
assert_equal ["id"], index.columns
end
end
def test_non_unique_index
with_example_table do
@conn.add_index 'ex', 'id', name: 'fun'
index = @conn.indexes('ex').find { |idx| idx.name == 'fun' }
assert_not index.unique, 'index is not unique'
@conn.add_index "ex", "id", name: "fun"
index = @conn.indexes("ex").find { |idx| idx.name == "fun" }
assert_not index.unique, "index is not unique"
end
end
def test_compound_index
with_example_table do
@conn.add_index 'ex', %w{ id number }, name: 'fun'
index = @conn.indexes('ex').find { |idx| idx.name == 'fun' }
@conn.add_index "ex", %w{ id number }, name: "fun"
index = @conn.indexes("ex").find { |idx| idx.name == "fun" }
assert_equal %w{ id number }.sort, index.columns.sort
end
end
def test_primary_key
with_example_table do
assert_equal 'id', @conn.primary_key('ex')
with_example_table 'internet integer PRIMARY KEY AUTOINCREMENT, number integer not null', 'foos' do
assert_equal 'internet', @conn.primary_key('foos')
assert_equal "id", @conn.primary_key("ex")
with_example_table "internet integer PRIMARY KEY AUTOINCREMENT, number integer not null", "foos" do
assert_equal "internet", @conn.primary_key("foos")
end
end
end
def test_no_primary_key
with_example_table 'number integer not null' do
assert_nil @conn.primary_key('ex')
with_example_table "number integer not null" do
assert_nil @conn.primary_key("ex")
end
end
def test_supports_extensions
assert_not @conn.supports_extensions?, 'does not support extensions'
assert_not @conn.supports_extensions?, "does not support extensions"
end
def test_respond_to_enable_extension
@ -402,15 +402,15 @@ def test_respond_to_disable_extension
def test_statement_closed
db = ::SQLite3::Database.new(ActiveRecord::Base.
configurations['arunit']['database'])
configurations["arunit"]["database"])
statement = ::SQLite3::Statement.new(db,
'CREATE TABLE statement_test (number integer not null)')
statement.stub(:step, ->{ raise ::SQLite3::BusyException.new('busy') }) do
"CREATE TABLE statement_test (number integer not null)")
statement.stub(:step, ->{ raise ::SQLite3::BusyException.new("busy") }) do
assert_called(statement, :columns, returns: []) do
assert_called(statement, :close) do
::SQLite3::Statement.stub(:new, statement) do
assert_raises ActiveRecord::StatementInvalid do
@conn.exec_query 'select * from statement_test'
@conn.exec_query "select * from statement_test"
end
end
end
@ -422,14 +422,14 @@ def test_statement_closed
def assert_logged logs
subscriber = SQLSubscriber.new
subscription = ActiveSupport::Notifications.subscribe('sql.active_record', subscriber)
subscription = ActiveSupport::Notifications.subscribe("sql.active_record", subscriber)
yield
assert_equal logs, subscriber.logged
ensure
ActiveSupport::Notifications.unsubscribe(subscription)
end
def with_example_table(definition = nil, table_name = 'ex', &block)
def with_example_table(definition = nil, table_name = "ex", &block)
definition ||= <<-SQL
id integer PRIMARY KEY AUTOINCREMENT,
number integer

@ -1,5 +1,5 @@
require "cases/helper"
require 'models/owner'
require "models/owner"
module ActiveRecord
module ConnectionAdapters
@ -9,11 +9,11 @@ def test_sqlite_creates_directory
begin
dir = Pathname.new(dir)
@conn = Base.sqlite3_connection :database => dir.join("db/foo.sqlite3"),
:adapter => 'sqlite3',
:adapter => "sqlite3",
:timeout => 100
assert Dir.exist? dir.join('db')
assert File.exist? dir.join('db/foo.sqlite3')
assert Dir.exist? dir.join("db")
assert File.exist? dir.join("db/foo.sqlite3")
ensure
@conn.disconnect! if @conn
end

@ -1,20 +1,20 @@
require 'cases/helper'
require "cases/helper"
class SQLite3StatementPoolTest < ActiveRecord::SQLite3TestCase
if Process.respond_to?(:fork)
def test_cache_is_per_pid
cache = ActiveRecord::ConnectionAdapters::SQLite3Adapter::StatementPool.new(10)
cache['foo'] = 'bar'
assert_equal 'bar', cache['foo']
cache["foo"] = "bar"
assert_equal "bar", cache["foo"]
pid = fork {
lookup = cache['foo'];
lookup = cache["foo"];
exit!(!lookup)
}
Process.waitpid pid
assert $?.success?, 'process should exit successfully'
assert $?.success?, "process should exit successfully"
end
end
end

@ -1,5 +1,5 @@
require "cases/helper"
require 'models/customer'
require "models/customer"
class AggregationsTest < ActiveRecord::TestCase
fixtures :customers
@ -51,17 +51,17 @@ def test_reloaded_instance_refreshes_aggregations
Customer.update_all("gps_location = '24x113'")
customers(:david).reload
assert_equal '24x113', customers(:david)['gps_location']
assert_equal "24x113", customers(:david)["gps_location"]
assert_equal GpsLocation.new('24x113'), customers(:david).gps_location
assert_equal GpsLocation.new("24x113"), customers(:david).gps_location
end
def test_gps_equality
assert_equal GpsLocation.new('39x110'), GpsLocation.new('39x110')
assert_equal GpsLocation.new("39x110"), GpsLocation.new("39x110")
end
def test_gps_inequality
assert_not_equal GpsLocation.new('39x110'), GpsLocation.new('39x111')
assert_not_equal GpsLocation.new("39x110"), GpsLocation.new("39x111")
end
def test_allow_nil_gps_is_nil
@ -102,7 +102,7 @@ def test_allow_nil_address_loaded_when_only_some_attributes_are_nil
end
def test_nil_assignment_results_in_nil
customers(:david).gps_location = GpsLocation.new('39x111')
customers(:david).gps_location = GpsLocation.new("39x111")
assert_not_nil customers(:david).gps_location
customers(:david).gps_location = nil
assert_nil customers(:david).gps_location
@ -129,13 +129,13 @@ def test_do_not_run_the_converter_when_nil_was_set
end
def test_custom_constructor
assert_equal 'Barney GUMBLE', customers(:barney).fullname.to_s
assert_equal "Barney GUMBLE", customers(:barney).fullname.to_s
assert_kind_of Fullname, customers(:barney).fullname
end
def test_custom_converter
customers(:barney).fullname = 'Barnoit Gumbleau'
assert_equal 'Barnoit GUMBLEAU', customers(:barney).fullname.to_s
customers(:barney).fullname = "Barnoit Gumbleau"
assert_equal "Barnoit GUMBLEAU", customers(:barney).fullname.to_s
assert_kind_of Fullname, customers(:barney).fullname
end
@ -158,7 +158,7 @@ class Person < ActiveRecord::Base
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

@ -100,8 +100,8 @@ def test_timestamps_without_null_set_null_to_false_on_create_table
end
end
assert !@connection.columns(:has_timestamps).find { |c| c.name == 'created_at' }.null
assert !@connection.columns(:has_timestamps).find { |c| c.name == 'updated_at' }.null
assert !@connection.columns(:has_timestamps).find { |c| c.name == "created_at" }.null
assert !@connection.columns(:has_timestamps).find { |c| c.name == "updated_at" }.null
end
def test_timestamps_without_null_set_null_to_false_on_change_table
@ -113,8 +113,8 @@ def test_timestamps_without_null_set_null_to_false_on_change_table
end
end
assert !@connection.columns(:has_timestamps).find { |c| c.name == 'created_at' }.null
assert !@connection.columns(:has_timestamps).find { |c| c.name == 'updated_at' }.null
assert !@connection.columns(:has_timestamps).find { |c| c.name == "created_at" }.null
assert !@connection.columns(:has_timestamps).find { |c| c.name == "updated_at" }.null
end
def test_timestamps_without_null_set_null_to_false_on_add_timestamps
@ -123,8 +123,8 @@ def test_timestamps_without_null_set_null_to_false_on_add_timestamps
add_timestamps :has_timestamps, default: Time.now
end
assert !@connection.columns(:has_timestamps).find { |c| c.name == 'created_at' }.null
assert !@connection.columns(:has_timestamps).find { |c| c.name == 'updated_at' }.null
assert !@connection.columns(:has_timestamps).find { |c| c.name == "created_at" }.null
assert !@connection.columns(:has_timestamps).find { |c| c.name == "updated_at" }.null
end
end
end

@ -1,11 +1,11 @@
require 'cases/helper'
require 'models/post'
require 'models/author'
require "cases/helper"
require "models/post"
require "models/author"
module ActiveRecord
module Associations
class AssociationScopeTest < ActiveRecord::TestCase
test 'does not duplicate conditions' do
test "does not duplicate conditions" do
scope = AssociationScope.scope(Author.new.association(:welcome_posts),
Author.connection)
binds = scope.where_clause.binds.map(&:value)

@ -1,28 +1,28 @@
require 'cases/helper'
require 'models/developer'
require 'models/project'
require 'models/company'
require 'models/topic'
require 'models/reply'
require 'models/computer'
require 'models/post'
require 'models/author'
require 'models/tag'
require 'models/tagging'
require 'models/comment'
require 'models/sponsor'
require 'models/member'
require 'models/essay'
require 'models/toy'
require 'models/invoice'
require 'models/line_item'
require 'models/column'
require 'models/record'
require 'models/admin'
require 'models/admin/user'
require 'models/ship'
require 'models/treasure'
require 'models/parrot'
require "cases/helper"
require "models/developer"
require "models/project"
require "models/company"
require "models/topic"
require "models/reply"
require "models/computer"
require "models/post"
require "models/author"
require "models/tag"
require "models/tagging"
require "models/comment"
require "models/sponsor"
require "models/member"
require "models/essay"
require "models/toy"
require "models/invoice"
require "models/line_item"
require "models/column"
require "models/record"
require "models/admin"
require "models/admin/user"
require "models/ship"
require "models/treasure"
require "models/parrot"
class BelongsToAssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :companies, :developers, :projects, :topics,
@ -43,7 +43,7 @@ def test_belongs_to_does_not_use_order_by
ActiveRecord::SQLCounter.clear_log
Client.find(3).firm
ensure
assert ActiveRecord::SQLCounter.log_all.all? { |sql| /order by/i !~ sql }, 'ORDER BY was used in the query'
assert ActiveRecord::SQLCounter.log_all.all? { |sql| /order by/i !~ sql }, "ORDER BY was used in the query"
end
def test_belongs_to_with_primary_key
@ -120,12 +120,12 @@ def test_default_scope_on_relations_is_not_cached
counter = 0
comments = Class.new(ActiveRecord::Base) {
self.table_name = 'comments'
self.inheritance_column = 'not_there'
self.table_name = "comments"
self.inheritance_column = "not_there"
posts = Class.new(ActiveRecord::Base) {
self.table_name = 'posts'
self.inheritance_column = 'not_there'
self.table_name = "posts"
self.inheritance_column = "not_there"
default_scope -> {
counter += 1
@ -166,7 +166,7 @@ def test_raises_type_mismatch_with_namespaced_class
Admin.const_set "Region", Class.new(ActiveRecord::Base)
e = assert_raise(ActiveRecord::AssociationTypeMismatch) {
Admin::RegionalUser.new(region: 'wrong value')
Admin::RegionalUser.new(region: "wrong value")
}
assert_match(/^Region\([^)]+\) expected, got "wrong value" which is an instance of String\([^)]+\)$/, e.message)
ensure
@ -325,7 +325,7 @@ def test_polymorphic_association_class
sponsor.association(:sponsorable).reload
assert_nil sponsor.sponsorable
sponsor.sponsorable_type = '' # the column doesn't have to be declared NOT NULL
sponsor.sponsorable_type = "" # the column doesn't have to be declared NOT NULL
assert_nil sponsor.association(:sponsorable).send(:klass)
sponsor.association(:sponsorable).reload
assert_nil sponsor.sponsorable
@ -352,10 +352,10 @@ def test_with_select
def test_belongs_to_without_counter_cache_option
# Ship has a conventionally named `treasures_count` column, but the counter_cache
# option is not given on the association.
ship = Ship.create(name: 'Countless')
ship = Ship.create(name: "Countless")
assert_no_difference lambda { ship.reload.treasures_count }, "treasures_count should not be changed unless counter_cache is given on the relation" do
treasure = Treasure.new(name: 'Gold', ship: ship)
treasure = Treasure.new(name: "Gold", ship: ship)
treasure.save
end
@ -820,7 +820,7 @@ def test_polymorphic_assignment_with_nil
assert_nil essay.writer_type
essay.writer_id = 1
essay.writer_type = 'Author'
essay.writer_type = "Author"
essay.writer = nil
assert_nil essay.writer_id
@ -872,11 +872,11 @@ def test_belongs_to_invalid_dependent_option_raises_exception
error = assert_raise ArgumentError do
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'
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
@ -930,7 +930,7 @@ def test_polymorphic_reassignment_of_associated_type_updates_the_object
assert !proxy.stale_target?
assert_equal members(:groucho), sponsor.sponsorable
sponsor.sponsorable_type = 'Firm'
sponsor.sponsorable_type = "Firm"
assert proxy.stale_target?
assert_equal companies(:first_firm), sponsor.sponsorable
@ -955,7 +955,7 @@ def test_polymorphic_counter_cache
comment = comments(:greetings)
assert_difference lambda { post.reload.tags_count }, -1 do
assert_difference 'comment.reload.tags_count', +1 do
assert_difference "comment.reload.tags_count", +1 do
tagging.taggable = comment
end
end
@ -1002,24 +1002,24 @@ 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
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
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
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
@ -1086,8 +1086,8 @@ def test_reflect_the_most_recent_change
assert_equal post.author_id, author2.id
end
test 'dangerous association name raises ArgumentError' do
[:errors, 'errors', :save, 'save'].each do |name|
test "dangerous association name raises ArgumentError" do
[:errors, "errors", :save, "save"].each do |name|
assert_raises(ArgumentError, "Association #{name} should not be allowed") do
Class.new(ActiveRecord::Base) do
belongs_to name
@ -1096,7 +1096,7 @@ def test_reflect_the_most_recent_change
end
end
test 'belongs_to works with model called Record' do
test "belongs_to works with model called Record" do
record = Record.create!
Column.create! record: record
assert_equal 1, Column.count

@ -1,5 +1,5 @@
require 'cases/helper'
require 'models/content'
require "cases/helper"
require "models/content"
class BidirectionalDestroyDependenciesTest < ActiveRecord::TestCase
fixtures :content, :content_positions

@ -1,10 +1,10 @@
require "cases/helper"
require 'models/post'
require 'models/author'
require 'models/project'
require 'models/developer'
require 'models/computer'
require 'models/company'
require "models/post"
require "models/author"
require "models/project"
require "models/developer"
require "models/computer"
require "models/company"
class AssociationCallbacksTest < ActiveRecord::TestCase
fixtures :posts, :authors, :projects, :developers
@ -115,7 +115,7 @@ def self.name; Project.name; end
}
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

@ -1,15 +1,15 @@
require "cases/helper"
require 'models/post'
require 'models/comment'
require 'models/author'
require 'models/categorization'
require 'models/category'
require 'models/company'
require 'models/topic'
require 'models/reply'
require 'models/person'
require 'models/vertex'
require 'models/edge'
require "models/post"
require "models/comment"
require "models/author"
require "models/categorization"
require "models/category"
require "models/company"
require "models/topic"
require "models/reply"
require "models/person"
require "models/vertex"
require "models/edge"
class CascadedEagerLoadingTest < ActiveRecord::TestCase
fixtures :authors, :mixins, :companies, :posts, :topics, :accounts, :comments,
@ -44,9 +44,9 @@ def test_eager_association_loading_with_hmt_does_not_table_name_collide_when_joi
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
@ -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
@ -125,7 +125,7 @@ def test_eager_association_loading_with_has_many_sti_and_subclasses
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

@ -1,11 +1,11 @@
require 'cases/helper'
require 'models/post'
require 'models/tagging'
require "cases/helper"
require "models/post"
require "models/tagging"
module Namespaced
class Post < ActiveRecord::Base
self.table_name = 'posts'
has_one :tagging, :as => :taggable, :class_name => 'Tagging'
self.table_name = "posts"
has_one :tagging, :as => :taggable, :class_name => "Tagging"
end
end
@ -16,7 +16,7 @@ def setup
end
def generate_test_objects
post = Namespaced::Post.create( :title => 'Great stuff', :body => 'This is not', :author_id => 1 )
post = Namespaced::Post.create( :title => "Great stuff", :body => "This is not", :author_id => 1 )
Tagging.create( :taggable => post )
end
@ -24,11 +24,11 @@ def test_class_names
old = ActiveRecord::Base.store_full_sti_class
ActiveRecord::Base.store_full_sti_class = false
post = Namespaced::Post.includes(:tagging).find_by_title('Great stuff')
post = Namespaced::Post.includes(:tagging).find_by_title("Great stuff")
assert_nil post.tagging
ActiveRecord::Base.store_full_sti_class = true
post = Namespaced::Post.includes(:tagging).find_by_title('Great stuff')
post = Namespaced::Post.includes(:tagging).find_by_title("Great stuff")
assert_instance_of Tagging, post.tagging
ensure
ActiveRecord::Base.store_full_sti_class = old

@ -1,11 +1,11 @@
require 'cases/helper'
require 'models/post'
require 'models/tag'
require 'models/author'
require 'models/comment'
require 'models/category'
require 'models/categorization'
require 'models/tagging'
require "cases/helper"
require "models/post"
require "models/tag"
require "models/author"
require "models/comment"
require "models/category"
require "models/categorization"
require "models/tagging"
module Remembered
extend ActiveSupport::Concern
@ -103,9 +103,9 @@ 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')
@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
@ -120,7 +120,7 @@ def test_missing_data_in_a_nested_include_should_not_cause_errors_when_construct
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
Author.all.merge!(:includes => includes, :where => {:authors => {:name => @davey_mcdave.name}}, :order => "categories.name").to_a
end
end
end

@ -1,31 +1,31 @@
require "cases/helper"
require 'models/post'
require 'models/tagging'
require 'models/tag'
require 'models/comment'
require 'models/author'
require 'models/essay'
require 'models/category'
require 'models/company'
require 'models/person'
require 'models/reader'
require 'models/owner'
require 'models/pet'
require 'models/reference'
require 'models/job'
require 'models/subscriber'
require 'models/subscription'
require 'models/book'
require 'models/developer'
require 'models/computer'
require 'models/project'
require 'models/member'
require 'models/membership'
require 'models/club'
require 'models/categorization'
require 'models/sponsor'
require 'models/mentor'
require 'models/contract'
require "models/post"
require "models/tagging"
require "models/tag"
require "models/comment"
require "models/author"
require "models/essay"
require "models/category"
require "models/company"
require "models/person"
require "models/reader"
require "models/owner"
require "models/pet"
require "models/reference"
require "models/job"
require "models/subscriber"
require "models/subscription"
require "models/book"
require "models/developer"
require "models/computer"
require "models/project"
require "models/member"
require "models/membership"
require "models/club"
require "models/categorization"
require "models/sponsor"
require "models/mentor"
require "models/contract"
class EagerAssociationTest < ActiveRecord::TestCase
fixtures :posts, :comments, :authors, :essays, :author_addresses, :categories, :categories_posts,
@ -54,7 +54,7 @@ def test_loading_with_one_association
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
@ -107,7 +107,7 @@ def test_loading_with_multiple_associations
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
@ -169,7 +169,7 @@ def test_load_associated_records_in_one_query_when_a_few_ids_passed
end
def test_including_duplicate_objects_from_belongs_to
popular_post = Post.create!(:title => 'foo', :body => "I like cars!")
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))
@ -182,12 +182,12 @@ def test_including_duplicate_objects_from_belongs_to
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 },
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
@ -195,10 +195,10 @@ def test_including_duplicate_objects_from_has_many
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)
assert_equal categories.map { |category| category.posts.first.special_comments.loaded? }, [true, true]
@ -256,7 +256,7 @@ def test_finding_with_includes_on_null_belongs_to_polymorphic_association
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.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) }
end
@ -302,17 +302,17 @@ def test_nested_loading_through_has_one_association
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
@ -354,45 +354,45 @@ 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
def test_eager_association_loading_with_belongs_to_and_conditions_string_with_unquoted_table_name
assert_nothing_raised do
Comment.includes(:post).references(:posts).where('posts.id = ?', 4)
Comment.includes(:post).references(:posts).where("posts.id = ?", 4)
end
end
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)
@ -402,7 +402,7 @@ def test_eager_association_loading_with_belongs_to_and_conditions_hash
end
def test_eager_association_loading_with_belongs_to_and_conditions_string_with_quoted_table_name
quoted_posts_id= Comment.connection.quote_table_name('posts') + '.' + Comment.connection.quote_column_name('id')
quoted_posts_id= Comment.connection.quote_table_name("posts") + "." + Comment.connection.quote_column_name("id")
assert_nothing_raised do
Comment.includes(:post).references(:posts).where("#{quoted_posts_id} = ?", 4)
end
@ -410,25 +410,25 @@ 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
def test_eager_association_loading_with_belongs_to_and_order_string_with_quoted_table_name
quoted_posts_id= Comment.connection.quote_table_name('posts') + '.' + Comment.connection.quote_column_name('id')
quoted_posts_id= Comment.connection.quote_table_name("posts") + "." + Comment.connection.quote_column_name("id")
assert_nothing_raised do
Comment.includes(:post).references(:posts).order(quoted_posts_id)
end
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
@ -493,14 +493,14 @@ def test_eager_load_belongs_to_with_string_keys
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 }
@ -516,19 +516,19 @@ def test_eager_with_has_many_through_a_belongs_to_association
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)
: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
@ -555,7 +555,7 @@ 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
@ -567,21 +567,21 @@ def test_eager_with_has_many_and_limit_and_conditions
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
def test_eager_with_has_many_and_limit_and_conditions_array_on_the_eagers
posts = Post.includes(:author, :comments).limit(2).references(:author).where("authors.name = ?", 'David')
posts = Post.includes(:author, :comments).limit(2).references(:author).where("authors.name = ?", "David")
assert_equal 2, posts.size
count = Post.includes(:author, :comments).limit(2).references(:author).where("authors.name = ?", 'David').count
count = Post.includes(:author, :comments).limit(2).references(:author).where("authors.name = ?", "David").count
assert_equal posts.size, count
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
@ -589,7 +589,7 @@ def test_eager_with_has_many_and_limit_and_high_offset_and_multiple_array_condit
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
:where => [ "authors.name = ? and comments.body = ?", "David", "go crazy" ]).to_a
assert_equal 0, posts.size
end
end
@ -597,13 +597,13 @@ def test_eager_with_has_many_and_limit_and_high_offset_and_multiple_array_condit
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
: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
@ -615,7 +615,7 @@ def test_eager_with_has_many_and_limit_with_no_results
def test_eager_count_performed_on_a_has_many_association_with_multi_table_conditional
author = authors(:david)
author_posts_without_comments = author.posts.select { |post| post.comments.blank? }
assert_equal author_posts_without_comments.size, author.posts.includes(:comments).where('comments.id is null').references(:comments).count
assert_equal author_posts_without_comments.size, author.posts.includes(:comments).where("comments.id is null").references(:comments).count
end
def test_eager_count_performed_on_a_has_many_through_association_with_multi_table_conditional
@ -746,7 +746,7 @@ def test_eager_with_invalid_association_reference
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)
@ -754,23 +754,23 @@ def test_eager_with_invalid_association_reference
end
def test_eager_has_many_through_with_order
tag = OrderedTag.create(name: 'Foo')
post1 = Post.create!(title: 'Beaches', body: "I like beaches!")
post2 = Post.create!(title: 'Pools', body: "I like pools!")
tag = OrderedTag.create(name: "Foo")
post1 = Post.create!(title: "Beaches", body: "I like beaches!")
post2 = Post.create!(title: "Pools", body: "I like pools!")
Tagging.create!(taggable_type: 'Post', taggable_id: post1.id, tag: tag)
Tagging.create!(taggable_type: 'Post', taggable_id: post2.id, tag: tag)
Tagging.create!(taggable_type: "Post", taggable_id: post1.id, tag: tag)
Tagging.create!(taggable_type: "Post", taggable_id: post2.id, tag: tag)
tag_with_includes = OrderedTag.includes(:tagged_posts).find(tag.id)
assert_equal(tag_with_includes.taggings.map(&:taggable).map(&:title), tag_with_includes.tagged_posts.map(&:title))
end
def test_eager_has_many_through_multiple_with_order
tag1 = OrderedTag.create!(name: 'Bar')
tag2 = OrderedTag.create!(name: 'Foo')
tag1 = OrderedTag.create!(name: "Bar")
tag2 = OrderedTag.create!(name: "Foo")
post1 = Post.create!(title: 'Beaches', body: "I like beaches!")
post2 = Post.create!(title: 'Pools', body: "I like pools!")
post1 = Post.create!(title: "Beaches", body: "I like beaches!")
post2 = Post.create!(title: "Pools", body: "I like pools!")
Tagging.create!(taggable: post1, tag: tag1)
Tagging.create!(taggable: post2, tag: tag1)
@ -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)
@ -811,7 +811,7 @@ def test_eager_with_default_scope_as_class_method_using_find_method
end
def test_eager_with_default_scope_as_class_method_using_find_by_method
developer = EagerDeveloperWithClassMethodDefaultScope.find_by(name: 'David')
developer = EagerDeveloperWithClassMethodDefaultScope.find_by(name: "David")
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)
@ -852,15 +852,15 @@ 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
@ -888,7 +888,7 @@ def test_limited_eager_with_numeric_in_association
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
:order => "people.id", :limit => 2, :offset => 0
).to_a
)
end
@ -947,7 +947,7 @@ 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
@ -1006,13 +1006,13 @@ def test_count_with_include
end
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
notifications = messages_for("instantiation.active_record") do
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
@ -1020,7 +1020,7 @@ def test_association_loading_notification
end
def test_base_messages
notifications = messages_for('instantiation.active_record') do
notifications = messages_for("instantiation.active_record") do
Developer.all.to_a
end
message = notifications.first
@ -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,30 +1071,30 @@ 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!")
post = Post.create!(:title => "Beaches", :body => "I like beaches!")
Reader.create! :person => people(:david), :post => post
LazyReader.create! :person => people(:susan), :post => post
@ -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,9 +1121,9 @@ 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 "David", posts[0].author_name
assert_equal posts(:welcome).comments, assert_no_queries { posts[0].comments}
end
@ -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,28 +1182,28 @@ 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? }
@ -1244,7 +1244,7 @@ def test_preloading_polymorphic_with_custom_foreign_type
end
def test_joins_with_includes_should_preload_via_joins
post = assert_queries(1) { Post.includes(:comments).joins(:comments).order('posts.id desc').to_a.first }
post = assert_queries(1) { Post.includes(:comments).joins(:comments).order("posts.id desc").to_a.first }
assert_queries(0) do
assert_not_equal 0, post.comments.to_a.count
@ -1291,7 +1291,7 @@ def test_eager_load_multiple_associations_with_references
test "preload ignores the scoping" do
assert_equal(
Comment.find(1).post,
Post.where('1 = 0').scoping { Comment.preload(:post).find(1).post }
Post.where("1 = 0").scoping { Comment.preload(:post).find(1).post }
)
end
@ -1316,10 +1316,10 @@ def test_eager_load_multiple_associations_with_references
end
test "works in combination with order(:symbol) and reorder(:symbol)" do
author = Author.includes(:posts).references(:posts).order(:name).find_by('posts.title IS NOT NULL')
author = Author.includes(:posts).references(:posts).order(:name).find_by("posts.title IS NOT NULL")
assert_equal authors(:bob), author
author = Author.includes(:posts).references(:posts).reorder(:name).find_by('posts.title IS NOT NULL')
author = Author.includes(:posts).references(:posts).reorder(:name).find_by("posts.title IS NOT NULL")
assert_equal authors(:bob), author
end
@ -1360,7 +1360,7 @@ def test_eager_load_multiple_associations_with_references
test "including associations with where.not adds implicit references" do
author = assert_queries(2) {
Author.includes(:posts).where.not(posts: { title: 'Welcome to the weblog'} ).last
Author.includes(:posts).where.not(posts: { title: "Welcome to the weblog"} ).last
}
assert_no_queries {
@ -1394,7 +1394,7 @@ def test_eager_load_multiple_associations_with_references
exception = assert_raises(ArgumentError) do
Author.preload(10).to_a
end
assert_equal('10 was not recognized for preload', exception.message)
assert_equal("10 was not recognized for preload", exception.message)
end
test "associations with extensions are not instance dependent" do
@ -1443,12 +1443,12 @@ def test_eager_load_multiple_associations_with_references
end
test "preloading a polymorphic association with references to the associated table" do
post = Post.includes(:tags).references(:tags).where('tags.name = ?', 'General').first
post = Post.includes(:tags).references(:tags).where("tags.name = ?", "General").first
assert_equal posts(:welcome), post
end
test "eager-loading a polymorphic association with references to the associated table" do
post = Post.eager_load(:tags).where('tags.name = ?', 'General').first
post = Post.eager_load(:tags).where("tags.name = ?", "General").first
assert_equal posts(:welcome), post
end

@ -1,10 +1,10 @@
require "cases/helper"
require 'models/post'
require 'models/comment'
require 'models/project'
require 'models/developer'
require 'models/computer'
require 'models/company_in_module'
require "models/post"
require "models/comment"
require "models/project"
require "models/developer"
require "models/computer"
require "models/company_in_module"
class AssociationsExtensionsTest < ActiveRecord::TestCase
fixtures :projects, :developers, :developers_projects, :comments, :posts
@ -63,14 +63,14 @@ def test_extension_name
extend!(Developer)
extend!(MyApplication::Business::Developer)
assert Object.const_get 'DeveloperAssociationNameAssociationExtension'
assert MyApplication::Business.const_get 'DeveloperAssociationNameAssociationExtension'
assert Object.const_get "DeveloperAssociationNameAssociationExtension"
assert MyApplication::Business.const_get "DeveloperAssociationNameAssociationExtension"
end
def test_proxy_association_after_scoped
post = posts(:welcome)
assert_equal post.association(:comments), post.comments.the_association
assert_equal post.association(:comments), post.comments.where('1=1').the_association
assert_equal post.association(:comments), post.comments.where("1=1").the_association
end
private

@ -1,38 +1,38 @@
require "cases/helper"
require 'models/developer'
require 'models/computer'
require 'models/project'
require 'models/company'
require 'models/course'
require 'models/customer'
require 'models/order'
require 'models/categorization'
require 'models/category'
require 'models/post'
require 'models/author'
require 'models/tag'
require 'models/tagging'
require 'models/parrot'
require 'models/person'
require 'models/pirate'
require 'models/professor'
require 'models/treasure'
require 'models/price_estimate'
require 'models/club'
require 'models/user'
require 'models/member'
require 'models/membership'
require 'models/sponsor'
require 'models/country'
require 'models/treaty'
require 'models/vertex'
require 'models/publisher'
require 'models/publisher/article'
require 'models/publisher/magazine'
require 'active_support/core_ext/string/conversions'
require "models/developer"
require "models/computer"
require "models/project"
require "models/company"
require "models/course"
require "models/customer"
require "models/order"
require "models/categorization"
require "models/category"
require "models/post"
require "models/author"
require "models/tag"
require "models/tagging"
require "models/parrot"
require "models/person"
require "models/pirate"
require "models/professor"
require "models/treasure"
require "models/price_estimate"
require "models/club"
require "models/user"
require "models/member"
require "models/membership"
require "models/sponsor"
require "models/country"
require "models/treaty"
require "models/vertex"
require "models/publisher"
require "models/publisher/article"
require "models/publisher/magazine"
require "active_support/core_ext/string/conversions"
class ProjectWithAfterCreateHook < ActiveRecord::Base
self.table_name = 'projects'
self.table_name = "projects"
has_and_belongs_to_many :developers,
:class_name => "DeveloperForProjectWithAfterCreateHook",
:join_table => "developers_projects",
@ -42,13 +42,13 @@ class ProjectWithAfterCreateHook < ActiveRecord::Base
after_create :add_david
def add_david
david = DeveloperForProjectWithAfterCreateHook.find_by_name('David')
david = DeveloperForProjectWithAfterCreateHook.find_by_name("David")
david.projects << self
end
end
class DeveloperForProjectWithAfterCreateHook < ActiveRecord::Base
self.table_name = 'developers'
self.table_name = "developers"
has_and_belongs_to_many :projects,
:class_name => "ProjectWithAfterCreateHook",
:join_table => "developers_projects",
@ -57,7 +57,7 @@ class DeveloperForProjectWithAfterCreateHook < ActiveRecord::Base
end
class ProjectWithSymbolsForKeys < ActiveRecord::Base
self.table_name = 'projects'
self.table_name = "projects"
has_and_belongs_to_many :developers,
:class_name => "DeveloperWithSymbolsForKeys",
:join_table => :developers_projects,
@ -66,7 +66,7 @@ class ProjectWithSymbolsForKeys < ActiveRecord::Base
end
class DeveloperWithSymbolsForKeys < ActiveRecord::Base
self.table_name = 'developers'
self.table_name = "developers"
has_and_belongs_to_many :projects,
:class_name => "ProjectWithSymbolsForKeys",
:join_table => :developers_projects,
@ -75,9 +75,9 @@ class DeveloperWithSymbolsForKeys < ActiveRecord::Base
end
class SubDeveloper < Developer
self.table_name = 'developers'
self.table_name = "developers"
has_and_belongs_to_many :special_projects,
:join_table => 'developers_projects',
:join_table => "developers_projects",
:foreign_key => "project_id",
:association_foreign_key => "developer_id"
end
@ -89,7 +89,7 @@ class DeveloperWithSymbolClassName < Developer
class DeveloperWithExtendOption < Developer
module NamedExtension
def category
'sns'
"sns"
end
end
@ -97,8 +97,8 @@ def category
end
class ProjectUnscopingDavidDefaultScope < ActiveRecord::Base
self.table_name = 'projects'
has_and_belongs_to_many :developers, -> { unscope(where: 'name') },
self.table_name = "projects"
has_and_belongs_to_many :developers, -> { unscope(where: "name") },
class_name: "LazyBlockDeveloperCalledDavid",
join_table: "developers_projects",
foreign_key: "project_id",
@ -110,14 +110,14 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
:parrots, :pirates, :parrots_pirates, :treasures, :price_estimates, :tags, :taggings, :computers
def setup_data_for_habtm_case
ActiveRecord::Base.connection.execute('delete from countries_treaties')
ActiveRecord::Base.connection.execute("delete from countries_treaties")
country = Country.new(:name => 'India')
country.country_id = 'c1'
country = Country.new(:name => "India")
country.country_id = "c1"
country.save!
treaty = Treaty.new(:name => 'peace')
treaty.treaty_id = 't1'
treaty = Treaty.new(:name => "peace")
treaty.treaty_id = "t1"
country.treaties << treaty
end
@ -131,29 +131,29 @@ def test_should_property_quote_string_primary_keys
setup_data_for_habtm_case
con = ActiveRecord::Base.connection
sql = 'select * from countries_treaties'
sql = "select * from countries_treaties"
record = con.select_rows(sql).last
assert_equal 'c1', record[0]
assert_equal 't1', record[1]
assert_equal "c1", record[0]
assert_equal "t1", record[1]
end
def test_proper_usage_of_primary_keys_and_join_table
setup_data_for_habtm_case
assert_equal 'country_id', Country.primary_key
assert_equal 'treaty_id', Treaty.primary_key
assert_equal "country_id", Country.primary_key
assert_equal "treaty_id", Treaty.primary_key
country = Country.first
assert_equal 1, country.treaties.count
end
def test_join_table_composite_primary_key_should_not_warn
country = Country.new(:name => 'India')
country.country_id = 'c1'
country = Country.new(:name => "India")
country.country_id = "c1"
country.save!
treaty = Treaty.new(:name => 'peace')
treaty.treaty_id = 't1'
treaty = Treaty.new(:name => "peace")
treaty.treaty_id = "t1"
warning = capture(:stderr) do
country.treaties << treaty
end
@ -285,7 +285,7 @@ def test_habtm_collection_size_from_build
def test_habtm_collection_size_from_params
devel = Developer.new({
projects_attributes: {
'0' => {}
"0" => {}
}
})
@ -362,16 +362,16 @@ 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
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
assert_equal "Yet Another Testing Title", another_post.title
end
def test_distinct_after_the_fact
@ -577,15 +577,15 @@ 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.find_by_name('Jamis')
assert_equal high_id_jamis, projects(:active_record).developers.find_by_name("Jamis")
end
def test_find_should_append_to_association_order
ordered_developers = projects(:active_record).developers.order('projects.id')
assert_equal ['developers.name desc, developers.id desc', 'projects.id'], ordered_developers.order_values
ordered_developers = projects(:active_record).developers.order("projects.id")
assert_equal ["developers.name desc, developers.id desc", "projects.id"], ordered_developers.order_values
end
def test_dynamic_find_all_should_respect_readonly_access
@ -594,8 +594,8 @@ def test_dynamic_find_all_should_respect_readonly_access
end
def test_new_with_values_in_collection
jamis = DeveloperForProjectWithAfterCreateHook.find_by_name('Jamis')
david = DeveloperForProjectWithAfterCreateHook.find_by_name('David')
jamis = DeveloperForProjectWithAfterCreateHook.find_by_name("Jamis")
david = DeveloperForProjectWithAfterCreateHook.find_by_name("David")
project = ProjectWithAfterCreateHook.new(:name => "Cooking with Bertie")
project.developers << jamis
project.save!
@ -613,8 +613,8 @@ def test_find_in_association_with_options
end
def test_association_with_extend_option
eponine = DeveloperWithExtendOption.create(name: 'Eponine')
assert_equal 'sns', eponine.projects.category
eponine = DeveloperWithExtendOption.create(name: "Eponine")
assert_equal "sns", eponine.projects.category
end
def test_replace_with_less
@ -690,7 +690,7 @@ def test_habtm_selects_all_columns_by_default
end
def test_habtm_respects_select_query_method
assert_equal ['id'], developers(:david).projects.select(:id).first.attributes.keys
assert_equal ["id"], developers(:david).projects.select(:id).first.attributes.keys
end
def test_join_table_alias
@ -702,7 +702,7 @@ def test_join_table_alias
3,
Developer.references(:developers_projects_join).merge(
:includes => {:projects => :developers},
:where => 'projects_developers_projects_join.joined_on IS NOT NULL'
:where => "projects_developers_projects_join.joined_on IS NOT NULL"
).to_a.size
)
end
@ -721,7 +721,7 @@ 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',
:includes => {:projects => :developers}, :where => "projects_developers_projects_join.joined_on IS NOT NULL",
:group => group.join(",")
).to_a.size
)
@ -729,7 +729,7 @@ def test_join_with_group
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
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
@ -776,7 +776,7 @@ def test_assign_ids
def test_assign_ids_ignoring_blanks
developer = Developer.new("name" => "Joe")
developer.project_ids = [projects(:active_record).id, nil, projects(:action_controller).id, '']
developer.project_ids = [projects(:active_record).id, nil, projects(:action_controller).id, ""]
developer.save
developer.reload
assert_equal 2, developer.projects.length
@ -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!
@ -810,7 +810,7 @@ def test_symbols_as_keys
def test_dynamic_find_should_respect_association_include
# SQL error in sort clause if :include is not included
# due to Unknown column 'authors.id'
assert Category.find(1).posts_with_authors_sorted_by_author_id.find_by_title('Welcome to the weblog')
assert Category.find(1).posts_with_authors_sorted_by_author_id.find_by_title("Welcome to the weblog")
end
def test_count
@ -872,7 +872,7 @@ def test_has_and_belongs_to_many_associations_on_new_records_use_null_relations
projects = Developer.new.projects
assert_no_queries(ignore_none: false) do
assert_equal [], projects
assert_equal [], projects.where(title: 'omg')
assert_equal [], projects.where(title: "omg")
assert_equal [], projects.pluck(:title)
assert_equal 0, projects.count
end
@ -886,7 +886,7 @@ def test_association_with_validate_false_does_not_run_associated_validation_call
treasure.valid?
assert_equal 1, treasure.rich_people.size
assert_nil rich_person.first_name, 'should not run associated person validation on create when validate: false'
assert_nil rich_person.first_name, "should not run associated person validation on create when validate: false"
end
def test_association_with_validate_false_does_not_run_associated_validation_callbacks_on_update
@ -899,11 +899,11 @@ def test_association_with_validate_false_does_not_run_associated_validation_call
treasure.valid?
assert_equal 1, treasure.rich_people.size
assert_equal person_first_name, rich_person.first_name, 'should not run associated person validation on update when validate: false'
assert_equal person_first_name, rich_person.first_name, "should not run associated person validation on update when validate: false"
end
def test_custom_join_table
assert_equal 'edges', Vertex.reflect_on_association(:sources).join_table
assert_equal "edges", Vertex.reflect_on_association(:sources).join_table
end
def test_has_and_belongs_to_many_in_a_namespaced_model_pointing_to_a_namespaced_model
@ -927,11 +927,11 @@ def test_has_and_belongs_to_many_in_a_namespaced_model_pointing_to_a_non_namespa
def test_redefine_habtm
child = SubDeveloper.new("name" => "Aredridel")
child.special_projects << SpecialProject.new("name" => "Special Project")
assert child.save, 'child object should be saved'
assert child.save, "child object should be saved"
end
def test_habtm_with_reflection_using_class_name_and_fixtures
assert_not_nil Developer._reflections['shared_computers']
assert_not_nil Developer._reflections["shared_computers"]
# Checking the fixture for named association is important here, because it's the only way
# we've been able to reproduce this bug
assert_not_nil File.read(File.expand_path("../../../fixtures/developers.yml", __FILE__)).index("shared_computers")

@ -1,43 +1,43 @@
require "cases/helper"
require 'models/developer'
require 'models/computer'
require 'models/project'
require 'models/company'
require 'models/contract'
require 'models/topic'
require 'models/reply'
require 'models/category'
require 'models/image'
require 'models/post'
require 'models/author'
require 'models/essay'
require 'models/comment'
require 'models/person'
require 'models/reader'
require 'models/tagging'
require 'models/tag'
require 'models/invoice'
require 'models/line_item'
require 'models/car'
require 'models/bulb'
require 'models/engine'
require 'models/categorization'
require 'models/minivan'
require 'models/speedometer'
require 'models/reference'
require 'models/job'
require 'models/college'
require 'models/student'
require 'models/pirate'
require 'models/ship'
require 'models/ship_part'
require 'models/treasure'
require 'models/parrot'
require 'models/tyre'
require 'models/subscriber'
require 'models/subscription'
require 'models/zine'
require 'models/interest'
require "models/developer"
require "models/computer"
require "models/project"
require "models/company"
require "models/contract"
require "models/topic"
require "models/reply"
require "models/category"
require "models/image"
require "models/post"
require "models/author"
require "models/essay"
require "models/comment"
require "models/person"
require "models/reader"
require "models/tagging"
require "models/tag"
require "models/invoice"
require "models/line_item"
require "models/car"
require "models/bulb"
require "models/engine"
require "models/categorization"
require "models/minivan"
require "models/speedometer"
require "models/reference"
require "models/job"
require "models/college"
require "models/student"
require "models/pirate"
require "models/ship"
require "models/ship_part"
require "models/treasure"
require "models/parrot"
require "models/tyre"
require "models/subscriber"
require "models/subscription"
require "models/zine"
require "models/interest"
class HasManyAssociationsTestForReorderWithJoinDependency < ActiveRecord::TestCase
fixtures :authors, :posts, :comments
@ -46,7 +46,7 @@ def test_should_generate_valid_sql
author = authors(:david)
# this can fail on adapters which require ORDER BY expressions to be included in the SELECT expression
# if the reorder clauses are not correctly handled
assert author.posts_with_comments_sorted_by_comment_id.where('comments.id > 0').reorder('posts.comments_count DESC', 'posts.tags_count DESC').last
assert author.posts_with_comments_sorted_by_comment_id.where("comments.id > 0").reorder("posts.comments_count DESC", "posts.tags_count DESC").last
end
end
@ -54,14 +54,14 @@ class HasManyAssociationsTestPrimaryKeys < ActiveRecord::TestCase
fixtures :authors, :essays, :subscribers, :subscriptions, :people
def test_custom_primary_key_on_new_record_should_fetch_with_query
subscriber = Subscriber.new(nick: 'webster132')
subscriber = Subscriber.new(nick: "webster132")
assert !subscriber.subscriptions.loaded?
assert_queries 1 do
assert_equal 2, subscriber.subscriptions.size
end
assert_equal subscriber.subscriptions, Subscription.where(subscriber_id: 'webster132')
assert_equal subscriber.subscriptions, Subscription.where(subscriber_id: "webster132")
end
def test_association_primary_key_on_new_record_should_fetch_with_query
@ -116,14 +116,14 @@ def test_sti_subselect_count
def test_anonymous_has_many
developer = Class.new(ActiveRecord::Base) {
self.table_name = 'developers'
self.table_name = "developers"
dev = self
developer_project = Class.new(ActiveRecord::Base) {
self.table_name = 'developers_projects'
self.table_name = "developers_projects"
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)
@ -135,20 +135,20 @@ def test_anonymous_has_many
def test_default_scope_on_relations_is_not_cached
counter = 0
posts = Class.new(ActiveRecord::Base) {
self.table_name = 'posts'
self.inheritance_column = 'not_there'
self.table_name = "posts"
self.inheritance_column = "not_there"
post = self
comments = Class.new(ActiveRecord::Base) {
self.table_name = 'comments'
self.inheritance_column = 'not_there'
self.table_name = "comments"
self.inheritance_column = "not_there"
belongs_to :post, :anonymous_class => post
default_scope -> {
counter += 1
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
@ -159,15 +159,15 @@ def test_default_scope_on_relations_is_not_cached
end
def test_has_many_build_with_options
college = College.create(name: 'UFMT')
Student.create(active: true, college_id: college.id, name: 'Sarah')
college = College.create(name: "UFMT")
Student.create(active: true, college_id: college.id, name: "Sarah")
assert_equal college.students, Student.where(active: true, college_id: college.id)
end
def test_add_record_to_collection_should_change_its_updated_at
ship = Ship.create(name: 'dauntless')
part = ShipPart.create(name: 'cockpit')
ship = Ship.create(name: "dauntless")
part = ShipPart.create(name: "cockpit")
updated_at = part.updated_at
travel(1.second) do
@ -181,8 +181,8 @@ def test_add_record_to_collection_should_change_its_updated_at
def test_clear_collection_should_not_change_updated_at
# GH#17161: .clear calls delete_all (and returns the association),
# which is intended to not touch associated objects's updated_at field
ship = Ship.create(name: 'dauntless')
part = ShipPart.create(name: 'cockpit', ship_id: ship.id)
ship = Ship.create(name: "dauntless")
part = ShipPart.create(name: "cockpit", ship_id: ship.id)
ship.parts.clear
part.reload
@ -192,27 +192,27 @@ def test_clear_collection_should_not_change_updated_at
end
def test_create_from_association_should_respect_default_scope
car = Car.create(:name => 'honda')
assert_equal 'honda', car.name
car = Car.create(:name => "honda")
assert_equal "honda", car.name
bulb = Bulb.create
assert_equal 'defaulty', bulb.name
assert_equal "defaulty", bulb.name
bulb = car.bulbs.build
assert_equal 'defaulty', bulb.name
assert_equal "defaulty", bulb.name
bulb = car.bulbs.create
assert_equal 'defaulty', bulb.name
assert_equal "defaulty", bulb.name
end
def test_build_and_create_from_association_should_respect_passed_attributes_over_default_scope
car = Car.create(name: 'honda')
car = Car.create(name: "honda")
bulb = car.bulbs.build(name: 'exotic')
assert_equal 'exotic', bulb.name
bulb = car.bulbs.build(name: "exotic")
assert_equal "exotic", bulb.name
bulb = car.bulbs.create(name: 'exotic')
assert_equal 'exotic', bulb.name
bulb = car.bulbs.create(name: "exotic")
assert_equal "exotic", bulb.name
bulb = car.awesome_bulbs.build(frickinawesome: false)
assert_equal false, bulb.frickinawesome
@ -225,24 +225,24 @@ def test_build_from_association_should_respect_scope
author = Author.new
post = author.thinking_posts.build
assert_equal 'So I was thinking', post.title
assert_equal "So I was thinking", post.title
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
assert_equal "defaulty", bulb.name
bulb = car.bulbs.build(nil)
assert_equal 'defaulty', bulb.name
assert_equal "defaulty", bulb.name
bulb = car.bulbs.create(nil)
assert_equal 'defaulty', bulb.name
assert_equal "defaulty", bulb.name
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 }
@ -314,7 +314,7 @@ 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
@ -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,7 +425,7 @@ 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
@ -441,7 +441,7 @@ def test_create_resets_cached_counters
def test_update_all_respects_association_scope
person = Person.new
person.first_name = 'Naruto'
person.first_name = "Naruto"
person.references << Reference.new
person.id = 10
person.references
@ -451,7 +451,7 @@ def test_update_all_respects_association_scope
def test_exists_respects_association_scope
person = Person.new
person.first_name = 'Sasuke'
person.first_name = "Sasuke"
person.references << Reference.new
person.id = 10
person.references
@ -497,13 +497,13 @@ def test_find_many_with_merged_options
end
def test_find_should_append_to_association_order
ordered_clients = companies(:first_firm).clients_sorted_desc.order('companies.id')
assert_equal ['id DESC', 'companies.id'], ordered_clients.order_values
ordered_clients = companies(:first_firm).clients_sorted_desc.order("companies.id")
assert_equal ["id DESC", "companies.id"], ordered_clients.order_values
end
def test_dynamic_find_should_respect_association_order
assert_equal companies(:another_first_firm_client), companies(:first_firm).clients_sorted_desc.where("type = 'Client'").first
assert_equal companies(:another_first_firm_client), companies(:first_firm).clients_sorted_desc.find_by_type('Client')
assert_equal companies(:another_first_firm_client), companies(:first_firm).clients_sorted_desc.find_by_type("Client")
end
def test_taking
@ -575,21 +575,21 @@ def test_finding_using_primary_key
end
def test_update_all_on_association_accessed_before_save
firm = Firm.new(name: 'Firm')
firm = Firm.new(name: "Firm")
clients_proxy_id = firm.clients.object_id
firm.clients << Client.first
firm.save!
assert_equal firm.clients.count, firm.clients.update_all(description: 'Great!')
assert_equal firm.clients.count, firm.clients.update_all(description: "Great!")
assert_not_equal clients_proxy_id, firm.clients.object_id
end
def test_update_all_on_association_accessed_before_save_with_explicit_foreign_key
# We can use the same cached proxy object because the id is available for the scope
firm = Firm.new(name: 'Firm', id: 100)
firm = Firm.new(name: "Firm", id: 100)
clients_proxy_id = firm.clients.object_id
firm.clients << Client.first
firm.save!
assert_equal firm.clients.count, firm.clients.update_all(description: 'Great!')
assert_equal firm.clients.count, firm.clients.update_all(description: "Great!")
assert_equal clients_proxy_id, firm.clients.object_id
end
@ -654,7 +654,7 @@ def test_find_each_with_conditions
firm = companies(:first_firm)
assert_queries(2) do
firm.clients.where(name: 'Microsoft').find_each(batch_size: 1) do |c|
firm.clients.where(name: "Microsoft").find_each(batch_size: 1) do |c|
assert_equal firm.id, c.firm_id
assert_equal "Microsoft", c.name
end
@ -695,13 +695,13 @@ def test_find_first
def test_find_first_sanitized
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
@ -712,7 +712,7 @@ def test_find_in_collection
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
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
@ -734,7 +734,7 @@ def test_default_select
end
def test_select_query_method
assert_equal ['id', 'body'], posts(:welcome).comments.select(:id, :body).first.attributes.keys
assert_equal ["id", "body"], posts(:welcome).comments.select(:id, :body).first.attributes.keys
end
def test_select_with_block
@ -993,7 +993,7 @@ def test_deleting_before_save
def test_has_many_without_counter_cache_option
# Ship has a conventionally named `treasures_count` column, but the counter_cache
# option is not given on the association.
ship = Ship.create(name: 'Countless', treasures_count: 10)
ship = Ship.create(name: "Countless", treasures_count: 10)
assert_not Ship.reflect_on_association(:treasures).has_cached_counter?
@ -1001,7 +1001,7 @@ def test_has_many_without_counter_cache_option
assert_equal ship.treasures.size, 0
assert_no_difference lambda { ship.reload.treasures_count }, "treasures_count should not be changed" do
ship.treasures.create(name: 'Gold')
ship.treasures.create(name: "Gold")
end
assert_no_difference lambda { ship.reload.treasures_count }, "treasures_count should not be changed" do
@ -1211,7 +1211,7 @@ def test_clearing_an_association_collection
def test_clearing_updates_counter_cache
topic = Topic.first
assert_difference 'topic.reload.replies_count', -1 do
assert_difference "topic.reload.replies_count", -1 do
topic.replies.clear
end
end
@ -1220,7 +1220,7 @@ def test_clearing_updates_counter_cache_when_inverse_counter_cache_is_a_symbol_w
car = Car.first
car.engines.create!
assert_difference 'car.reload.engines_count', -1 do
assert_difference "car.reload.engines_count", -1 do
car.engines.clear
end
end
@ -1329,12 +1329,12 @@ def test_creation_respects_hash_condition
ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.build
assert ms_client.save
assert_equal 'Microsoft', ms_client.name
assert_equal "Microsoft", ms_client.name
another_ms_client = companies(:first_firm).clients_like_ms_with_hash_conditions.create
assert another_ms_client.persisted?
assert_equal 'Microsoft', another_ms_client.name
assert_equal "Microsoft", another_ms_client.name
end
def test_clearing_without_initial_access
@ -1351,7 +1351,7 @@ def test_deleting_a_item_which_is_not_in_the_collection
assert_predicate companies(:first_firm).clients_of_firm, :loaded?
summit = Client.find_by_name('Summit')
summit = Client.find_by_name("Summit")
companies(:first_firm).clients_of_firm.delete(summit)
assert_equal 2, companies(:first_firm).clients_of_firm.size
assert_equal 2, companies(:first_firm).clients_of_firm.reload.size
@ -1361,7 +1361,7 @@ def test_deleting_a_item_which_is_not_in_the_collection
def test_deleting_by_integer_id
david = Developer.find(1)
assert_difference 'david.projects.count', -1 do
assert_difference "david.projects.count", -1 do
assert_equal 1, david.projects.delete(1).size
end
@ -1371,8 +1371,8 @@ def test_deleting_by_integer_id
def test_deleting_by_string_id
david = Developer.find(1)
assert_difference 'david.projects.count', -1 do
assert_equal 1, david.projects.delete('1').size
assert_difference "david.projects.count", -1 do
assert_equal 1, david.projects.delete("1").size
end
assert_equal 1, david.projects.size
@ -1462,7 +1462,7 @@ def test_dependence
def test_dependence_for_associations_with_hash_condition
david = authors(:david)
assert_difference('Post.count', -1) { assert david.destroy }
assert_difference("Post.count", -1) { assert david.destroy }
end
def test_destroy_dependent_when_deleted_from_association
@ -1518,21 +1518,21 @@ 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
I18n.backend = I18n::Backend::Simple.new
I18n.backend.store_translations :en, activerecord: { errors: { messages: { restrict_dependent_destroy: { many: 'message for deprecated key' } } } }
I18n.backend.store_translations :en, activerecord: { errors: { messages: { restrict_dependent_destroy: { many: "message for deprecated key" } } } }
firm = RestrictedWithErrorFirm.create!(name: 'restrict')
firm.companies.create(name: 'child')
firm = RestrictedWithErrorFirm.create!(name: "restrict")
firm.companies.create(name: "child")
assert !firm.companies.empty?
@ -1540,16 +1540,16 @@ def test_restrict_with_error_is_deprecated_using_key_many
assert !firm.errors.empty?
assert_equal 'message for deprecated key', firm.errors[:base].first
assert RestrictedWithErrorFirm.exists?(name: 'restrict')
assert firm.companies.exists?(name: 'child')
assert_equal "message for deprecated key", firm.errors[:base].first
assert RestrictedWithErrorFirm.exists?(name: "restrict")
assert firm.companies.exists?(name: "child")
ensure
I18n.backend.reload!
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,15 +1558,15 @@ 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
I18n.backend = I18n::Backend::Simple.new
I18n.backend.store_translations 'en', activerecord: {attributes: {restricted_with_error_firm: {companies: 'client companies'}}}
firm = RestrictedWithErrorFirm.create!(name: 'restrict')
firm.companies.create(name: 'child')
I18n.backend.store_translations "en", activerecord: {attributes: {restricted_with_error_firm: {companies: "client companies"}}}
firm = RestrictedWithErrorFirm.create!(name: "restrict")
firm.companies.create(name: "child")
assert !firm.companies.empty?
@ -1575,8 +1575,8 @@ def test_restrict_with_error_with_locale
assert !firm.errors.empty?
assert_equal "Cannot delete record because dependent client 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")
ensure
I18n.backend.reload!
end
@ -1586,10 +1586,10 @@ 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'
"includes a client that does not belong to any firm"
end
def test_adding_array_and_collection
@ -1644,7 +1644,7 @@ def test_replace_with_same_content
firm.clients = []
end
assert_equal [], firm.send('clients=', [])
assert_equal [], firm.send("clients=", [])
end
def test_transactions_when_replacing_on_persisted
@ -1724,8 +1724,8 @@ 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.client_ids = [companies(:first_client).id, nil, companies(:second_client).id, '']
firm = Firm.create!(:name => "Apple")
firm.client_ids = [companies(:first_client).id, nil, companies(:second_client).id, ""]
firm.save!
assert_equal 2, firm.clients.reload.size
@ -1747,7 +1747,7 @@ def test_modifying_a_through_a_has_many_should_raise
def test_dynamic_find_should_respect_association_order_for_through
assert_equal Comment.find(10), authors(:david).comments_desc.where("comments.type = 'SpecialComment'").first
assert_equal Comment.find(10), authors(:david).comments_desc.find_by_type('SpecialComment')
assert_equal Comment.find(10), authors(:david).comments_desc.find_by_type("SpecialComment")
end
def test_has_many_through_respects_hash_conditions
@ -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,8 +1978,8 @@ 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",
@ -2011,7 +2011,7 @@ def test_respond_to_private_class_methods
def test_creating_using_primary_key
firm = Firm.all.merge!(:order => "id").first
client = firm.clients_using_primary_key.create!(:name => 'test')
client = firm.clients_using_primary_key.create!(:name => "test")
assert_equal firm.name, client.firm_name
end
@ -2039,7 +2039,7 @@ def test_attributes_are_being_set_when_initialized_from_has_many_association_wit
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
@ -2096,7 +2096,7 @@ def test_abstract_class_with_polymorphic_has_many
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,10 +2106,10 @@ 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
assert_equal "Post", tagging.taggable_type
end
def test_dont_call_save_callbacks_twice_on_has_many
@ -2121,30 +2121,30 @@ 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']
assert_equal car.id, bulb.attributes_after_initialize["car_id"]
end
def test_attributes_are_set_when_initialized_from_has_many_null_relationship
car = Car.new name: 'honda'
bulb = car.bulbs.where(name: 'headlight').first_or_initialize
assert_equal 'headlight', bulb.name
car = Car.new name: "honda"
bulb = car.bulbs.where(name: "headlight").first_or_initialize
assert_equal "headlight", bulb.name
end
def test_attributes_are_set_when_initialized_from_polymorphic_has_many_null_relationship
post = Post.new title: 'title', body: 'bar'
tag = Tag.create!(name: 'foo')
post = Post.new title: "title", body: "bar"
tag = Tag.create!(name: "foo")
tagging = post.taggings.where(tag: tag).first_or_initialize
assert_equal tag.id, tagging.tag_id
assert_equal 'Post', tagging.taggable_type
assert_equal "Post", tagging.taggable_type
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
@ -2172,15 +2172,15 @@ def test_collection_association_with_private_kernel_method
end
test "first_or_initialize adds the record to the association" do
firm = Firm.create! name: 'omg'
firm = Firm.create! name: "omg"
client = firm.clients_of_firm.first_or_initialize
assert_equal [client], firm.clients_of_firm
end
test "first_or_create adds the record to the association" do
firm = Firm.create! name: 'omg'
firm = Firm.create! name: "omg"
firm.clients_of_firm.load_target
client = firm.clients_of_firm.first_or_create name: 'lol'
client = firm.clients_of_firm.first_or_create name: "lol"
assert_equal [client], firm.clients_of_firm
assert_equal [client], firm.reload.clients_of_firm
end
@ -2202,7 +2202,7 @@ def test_collection_association_with_private_kernel_method
assert_no_queries(ignore_none: false) do
assert_equal [], post.comments
assert_equal [], post.comments.where(body: 'omg')
assert_equal [], post.comments.where(body: "omg")
assert_equal [], post.comments.pluck(:body)
assert_equal 0, post.comments.sum(:id)
assert_equal 0, post.comments.count
@ -2230,7 +2230,7 @@ def test_collection_association_with_private_kernel_method
david = authors(:david)
post = david.posts.first
post.type = 'PostWithSpecialCategorization'
post.type = "PostWithSpecialCategorization"
post.save
categorization = post.categorizations.first
@ -2243,8 +2243,8 @@ def test_collection_association_with_private_kernel_method
end
test "does not duplicate associations when used with natural primary keys" do
speedometer = Speedometer.create!(id: '4')
speedometer.minivans.create!(minivan_id: 'a-van-red' ,name: 'a van', color: 'red')
speedometer = Speedometer.create!(id: "4")
speedometer.minivans.create!(minivan_id: "a-van-red" ,name: "a van", color: "red")
assert_equal 1, speedometer.minivans.to_a.size, "Only one association should be present:\n#{speedometer.minivans.to_a}"
assert_equal 1, speedometer.reload.minivans.to_a.size
@ -2260,7 +2260,7 @@ def test_collection_association_with_private_kernel_method
end
test "can unscope and where the default scope of the associated model" do
Car.has_many :other_bulbs, -> { unscope(where: [:name]).where(name: 'other') }, class_name: "Bulb"
Car.has_many :other_bulbs, -> { unscope(where: [:name]).where(name: "other") }, class_name: "Bulb"
car = Car.create!
bulb1 = Bulb.create! name: "defaulty", car: car
bulb2 = Bulb.create! name: "other", car: car
@ -2270,7 +2270,7 @@ def test_collection_association_with_private_kernel_method
end
test "can rewhere the default scope of the associated model" do
Car.has_many :old_bulbs, -> { rewhere(name: 'old') }, class_name: "Bulb"
Car.has_many :old_bulbs, -> { rewhere(name: "old") }, class_name: "Bulb"
car = Car.create!
bulb1 = Bulb.create! name: "defaulty", car: car
bulb2 = Bulb.create! name: "old", car: car
@ -2279,7 +2279,7 @@ def test_collection_association_with_private_kernel_method
assert_equal [bulb2], car.old_bulbs
end
test 'unscopes the default scope of associated model when used with include' do
test "unscopes the default scope of associated model when used with include" do
car = Car.create!
bulb = Bulb.create! name: "other", car: car
@ -2299,7 +2299,7 @@ def test_collection_association_with_private_kernel_method
assert_equal "Failed to destroy the record", error.message
end
test 'updates counter cache when default scope is given' do
test "updates counter cache when default scope is given" do
topic = DefaultRejectedTopic.create approved: true
assert_difference "topic.reload.replies_count", 1 do
@ -2307,8 +2307,8 @@ def test_collection_association_with_private_kernel_method
end
end
test 'dangerous association name raises ArgumentError' do
[:errors, 'errors', :save, 'save'].each do |name|
test "dangerous association name raises ArgumentError" do
[:errors, "errors", :save, "save"].each do |name|
assert_raises(ArgumentError, "Association #{name} should not be allowed") do
Class.new(ActiveRecord::Base) do
has_many name
@ -2317,7 +2317,7 @@ def test_collection_association_with_private_kernel_method
end
end
test 'passes custom context validation to validate children' do
test "passes custom context validation to validate children" do
pirate = FamousPirate.new
pirate.famous_ships << ship = FamousShip.new
@ -2326,7 +2326,7 @@ def test_collection_association_with_private_kernel_method
assert_equal "can't be blank", ship.errors[:name].first
end
test 'association with instance dependent scope' do
test "association with instance dependent scope" do
bob = authors(:bob)
Post.create!(title: "signed post by bob", body: "stuff", author: authors(:bob))
Post.create!(title: "anonymous post", body: "more stuff", author: authors(:bob))
@ -2336,7 +2336,7 @@ def test_collection_association_with_private_kernel_method
assert_equal [], authors(:david).posts_with_signature.map(&:title)
end
test 'associations autosaves when object is already persisted' do
test "associations autosaves when object is already persisted" do
bulb = Bulb.create!
tyre = Tyre.create!
@ -2349,7 +2349,7 @@ def test_collection_association_with_private_kernel_method
assert_equal 1, car.tyres.count
end
test 'associations replace in memory when records have the same id' do
test "associations replace in memory when records have the same id" do
bulb = Bulb.create!
car = Car.create!(bulbs: [bulb])
@ -2360,7 +2360,7 @@ def test_collection_association_with_private_kernel_method
assert_equal "foo", car.bulbs.first.name
end
test 'in memory replacement executes no queries' do
test "in memory replacement executes no queries" do
bulb = Bulb.create!
car = Car.create!(bulbs: [bulb])
@ -2371,7 +2371,7 @@ def test_collection_association_with_private_kernel_method
end
end
test 'in memory replacements do not execute callbacks' do
test "in memory replacements do not execute callbacks" do
raise_after_add = false
klass = Class.new(ActiveRecord::Base) do
self.table_name = :cars
@ -2392,7 +2392,7 @@ def self.name
end
end
test 'in memory replacements sets inverse instance' do
test "in memory replacements sets inverse instance" do
bulb = Bulb.create!
car = Car.create!(bulbs: [bulb])
@ -2402,7 +2402,7 @@ def self.name
assert_same car, new_bulb.car
end
test 'in memory replacement maintains order' do
test "in memory replacement maintains order" do
first_bulb = Bulb.create!
second_bulb = Bulb.create!
car = Car.create!(bulbs: [first_bulb, second_bulb])
@ -2413,7 +2413,7 @@ def self.name
assert_equal [first_bulb, second_bulb], car.bulbs
end
test 'double insertion of new object to association when same association used in the after create callback of a new object' do
test "double insertion of new object to association when same association used in the after create callback of a new object" do
car = Car.create!
car.bulbs << TrickyBulb.new
assert_equal 1, car.bulbs.size
@ -2456,7 +2456,7 @@ def test_destroy_with_bang_bubbles_errors_from_associations
end
def test_ids_reader_memoization
car = Car.create!(name: 'Tofaş')
car = Car.create!(name: "Tofaş")
bulb = Bulb.create!(car: car)
assert_equal [bulb.id], car.bulb_ids

@ -1,33 +1,33 @@
require "cases/helper"
require 'models/post'
require 'models/person'
require 'models/reference'
require 'models/job'
require 'models/reader'
require 'models/comment'
require 'models/rating'
require 'models/tag'
require 'models/tagging'
require 'models/author'
require 'models/owner'
require 'models/pet'
require 'models/pet_treasure'
require 'models/toy'
require 'models/treasure'
require 'models/contract'
require 'models/company'
require 'models/developer'
require 'models/computer'
require 'models/subscriber'
require 'models/book'
require 'models/subscription'
require 'models/essay'
require 'models/category'
require 'models/categorization'
require 'models/member'
require 'models/membership'
require 'models/club'
require 'models/organization'
require "models/post"
require "models/person"
require "models/reference"
require "models/job"
require "models/reader"
require "models/comment"
require "models/rating"
require "models/tag"
require "models/tagging"
require "models/author"
require "models/owner"
require "models/pet"
require "models/pet_treasure"
require "models/toy"
require "models/treasure"
require "models/contract"
require "models/company"
require "models/developer"
require "models/computer"
require "models/subscriber"
require "models/book"
require "models/subscription"
require "models/essay"
require "models/category"
require "models/categorization"
require "models/member"
require "models/membership"
require "models/club"
require "models/organization"
class HasManyThroughAssociationsTest < ActiveRecord::TestCase
fixtures :posts, :readers, :people, :comments, :authors, :categories, :taggings, :tags,
@ -37,7 +37,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
# Dummies to force column loads so query counts are clean.
def setup
Person.create :first_name => 'gummy'
Person.create :first_name => "gummy"
Reader.create :person_id => 0, :post_id => 0
end
@ -49,9 +49,9 @@ def test_preload_sti_rhs_class
end
def test_preload_sti_middle_relation
club = Club.create!(name: 'Aaron cool banana club')
member1 = Member.create!(name: 'Aaron')
member2 = Member.create!(name: 'Cat')
club = Club.create!(name: "Aaron cool banana club")
member1 = Member.create!(name: "Aaron")
member2 = Member.create!(name: "Cat")
SuperMembership.create! club: club, member: member1
CurrentMembership.create! club: club, member: member2
@ -67,10 +67,10 @@ def make_model(name)
def test_ordered_has_many_through
person_prime = Class.new(ActiveRecord::Base) do
def self.name; 'Person'; end
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
@ -85,7 +85,7 @@ def test_singleton_has_many_through
subscription = make_model "Subscription"
subscriber = make_model "Subscriber"
subscriber.primary_key = 'nick'
subscriber.primary_key = "nick"
subscription.belongs_to :book, anonymous_class: book
subscription.belongs_to :subscriber, anonymous_class: subscriber
@ -124,8 +124,8 @@ def test_no_pk_join_table_delete
sicp.students.reload
assert_operator lesson_student.count, :>=, 2
assert_no_difference('student.count') do
assert_difference('lesson_student.count', -2) do
assert_no_difference("student.count") do
assert_difference("lesson_student.count", -2) do
sicp.students.destroy(*student.all.to_a)
end
end
@ -150,11 +150,11 @@ def test_no_pk_join_model_callbacks
end
def make_no_pk_hm_t
lesson = make_model 'Lesson'
student = make_model 'Student'
lesson = make_model "Lesson"
student = make_model "Student"
lesson_student = make_model 'LessonStudent'
lesson_student.table_name = 'lessons_students'
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
@ -197,8 +197,8 @@ def test_delete_all_for_with_dependent_option_destroy
person = people(:david)
assert_equal 1, person.jobs_with_dependent_destroy.count
assert_no_difference 'Job.count' do
assert_difference 'Reference.count', -1 do
assert_no_difference "Job.count" do
assert_difference "Reference.count", -1 do
person.reload.jobs_with_dependent_destroy.delete_all
end
end
@ -208,8 +208,8 @@ def test_delete_all_for_with_dependent_option_nullify
person = people(:david)
assert_equal 1, person.jobs_with_dependent_nullify.count
assert_no_difference 'Job.count' do
assert_no_difference 'Reference.count' do
assert_no_difference "Job.count" do
assert_no_difference "Reference.count" do
person.reload.jobs_with_dependent_nullify.delete_all
end
end
@ -219,8 +219,8 @@ def test_delete_all_for_with_dependent_option_delete_all
person = people(:david)
assert_equal 1, person.jobs_with_dependent_delete_all.count
assert_no_difference 'Job.count' do
assert_difference 'Reference.count', -1 do
assert_no_difference "Job.count" do
assert_difference "Reference.count", -1 do
person.reload.jobs_with_dependent_delete_all.delete_all
end
end
@ -238,7 +238,7 @@ def test_associate_existing_record_twice_should_add_to_target_twice
post = posts(:thinking)
person = people(:david)
assert_difference 'post.people.to_a.count', 2 do
assert_difference "post.people.to_a.count", 2 do
post.people << person
post.people << person
end
@ -248,7 +248,7 @@ def test_associate_existing_record_twice_should_add_records_twice
post = posts(:thinking)
person = people(:david)
assert_difference 'post.people.count', 2 do
assert_difference "post.people.count", 2 do
post.people << person
post.people << person
end
@ -261,7 +261,7 @@ def test_add_two_instance_and_then_deleting
post.people << person
post.people << person
counts = ['post.people.count', 'post.people.to_a.count', 'post.readers.count', 'post.readers.to_a.count']
counts = ["post.people.count", "post.people.to_a.count", "post.readers.count", "post.readers.to_a.count"]
assert_difference counts, -2 do
post.people.delete(person)
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
@ -308,7 +308,7 @@ def test_associate_new_by_building
# * 2 new records = 4
# + 1 query to save the actual post = 5
assert_queries(5) do
posts(:thinking).body += '-changed'
posts(:thinking).body += "-changed"
posts(:thinking).save
end
@ -335,8 +335,8 @@ def test_build_then_save_with_has_one_inverse
end
def test_both_parent_ids_set_when_saving_new
post = Post.new(title: 'Hello', body: 'world')
person = Person.new(first_name: 'Sean')
post = Post.new(title: "Hello", body: "world")
person = Person.new(first_name: "Sean")
post.people = [person]
post.save
@ -396,8 +396,8 @@ def test_delete_through_belongs_to_with_dependent_nullify
job = jobs(:magician)
reference = Reference.where(:job_id => job.id, :person_id => person.id).first
assert_no_difference ['Job.count', 'Reference.count'] do
assert_difference 'person.jobs.count', -1 do
assert_no_difference ["Job.count", "Reference.count"] do
assert_difference "person.jobs.count", -1 do
person.jobs_with_dependent_nullify.delete(job)
end
end
@ -416,8 +416,8 @@ def test_delete_through_belongs_to_with_dependent_delete_all
# Make sure we're not deleting everything
assert person.jobs.count >= 2
assert_no_difference 'Job.count' do
assert_difference ['person.jobs.count', 'Reference.count'], -1 do
assert_no_difference "Job.count" do
assert_difference ["person.jobs.count", "Reference.count"], -1 do
person.jobs_with_dependent_delete_all.delete(job)
end
end
@ -437,8 +437,8 @@ def test_delete_through_belongs_to_with_dependent_destroy
# Make sure we're not deleting everything
assert person.jobs.count >= 2
assert_no_difference 'Job.count' do
assert_difference ['person.jobs.count', 'Reference.count'], -1 do
assert_no_difference "Job.count" do
assert_difference ["person.jobs.count", "Reference.count"], -1 do
person.jobs_with_dependent_destroy.delete(job)
end
end
@ -455,8 +455,8 @@ def test_belongs_to_with_dependent_destroy
# Create a reference which is not linked to a job. This should not be destroyed.
person.references.create!
assert_no_difference 'Job.count' do
assert_difference 'Reference.count', -person.jobs.count do
assert_no_difference "Job.count" do
assert_difference "Reference.count", -person.jobs.count do
person.destroy
end
end
@ -468,8 +468,8 @@ def test_belongs_to_with_dependent_delete_all
# Create a reference which is not linked to a job. This should not be destroyed.
person.references.create!
assert_no_difference 'Job.count' do
assert_difference 'Reference.count', -person.jobs.count do
assert_no_difference "Job.count" do
assert_difference "Reference.count", -person.jobs.count do
person.destroy
end
end
@ -480,7 +480,7 @@ def test_belongs_to_with_dependent_nullify
references = person.references.to_a
assert_no_difference ['Reference.count', 'Job.count'] do
assert_no_difference ["Reference.count", "Job.count"] do
person.destroy
end
@ -491,30 +491,30 @@ 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
assert_difference ["post.reload.tags_count"], -1 do
posts(:welcome).tags.delete(tag)
end
end
def test_update_counter_caches_on_delete_with_dependent_destroy
post = posts(:welcome)
tag = post.tags.create!(:name => 'doomed')
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
assert_difference ["post.reload.tags_with_destroy_count"], -1 do
posts(:welcome).tags_with_destroy.delete(tag)
end
end
def test_update_counter_caches_on_delete_with_dependent_nullify
post = posts(:welcome)
tag = post.tags.create!(:name => 'doomed')
tag = post.tags.create!(:name => "doomed")
post.update_columns(tags_with_nullify_count: post.tags.count)
assert_no_difference 'post.reload.tags_count' do
assert_difference 'post.reload.tags_with_nullify_count', -1 do
assert_no_difference "post.reload.tags_count" do
assert_difference "post.reload.tags_with_nullify_count", -1 do
posts(:welcome).tags_with_nullify.delete(tag)
end
end
@ -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 = []
@ -533,9 +533,9 @@ def test_update_counter_caches_on_replace_association
def test_update_counter_caches_on_destroy
post = posts(:welcome)
tag = post.tags.create!(name: 'doomed')
tag = post.tags.create!(name: "doomed")
assert_difference 'post.reload.tags_count', -1 do
assert_difference "post.reload.tags_count", -1 do
tag.tagged_posts.destroy(post)
end
end
@ -561,23 +561,23 @@ def test_replace_association
def test_replace_order_is_preserved
posts(:welcome).people.clear
posts(:welcome).people = [people(:david), people(:michael)]
assert_equal [people(:david).id, people(:michael).id], posts(:welcome).readers.order('id').map(&:person_id)
assert_equal [people(:david).id, people(:michael).id], posts(:welcome).readers.order("id").map(&:person_id)
# Test the inverse order in case the first success was a coincidence
posts(:welcome).people.clear
posts(:welcome).people = [people(:michael), people(:david)]
assert_equal [people(:michael).id, people(:david).id], posts(:welcome).readers.order('id').map(&:person_id)
assert_equal [people(:michael).id, people(:david).id], posts(:welcome).readers.order("id").map(&:person_id)
end
def test_replace_by_id_order_is_preserved
posts(:welcome).people.clear
posts(:welcome).person_ids = [people(:david).id, people(:michael).id]
assert_equal [people(:david).id, people(:michael).id], posts(:welcome).readers.order('id').map(&:person_id)
assert_equal [people(:david).id, people(:michael).id], posts(:welcome).readers.order("id").map(&:person_id)
# Test the inverse order in case the first success was a coincidence
posts(:welcome).people.clear
posts(:welcome).person_ids = [people(:michael).id, people(:david).id]
assert_equal [people(:michael).id, people(:david).id], posts(:welcome).readers.order('id').map(&:person_id)
assert_equal [people(:michael).id, people(:david).id], posts(:welcome).readers.order("id").map(&:person_id)
end
def test_associate_with_create
@ -605,19 +605,19 @@ 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
@ -633,38 +633,38 @@ def test_create_on_new_record
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
repair_validations(Contract) do
Contract.validate {|r| r.errors[:base] << 'Invalid Contract' }
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
@ -729,7 +729,7 @@ def test_association_callback_ordering
def test_dynamic_find_should_respect_association_include
# SQL error in sort clause if :include is not included
# due to Unknown column 'comments.id'
assert Person.find(1).posts_with_comments_sorted_by_comment_id.find_by_title('Welcome to the weblog')
assert Person.find(1).posts_with_comments_sorted_by_comment_id.find_by_title("Welcome to the weblog")
end
def test_count_with_include_should_alias_join_table
@ -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
@ -816,8 +816,8 @@ def test_modifying_has_many_through_has_one_reflection_should_raise
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
@ -899,7 +899,7 @@ def test_attributes_are_being_set_when_initialized_from_hm_through_association_w
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
@ -932,7 +932,7 @@ def test_can_update_through_association
def test_has_many_through_polymorphic_with_primary_key_option
assert_equal [categories(:general)], authors(:david).essay_categories
authors = Author.joins(:essay_categories).where('categories.id' => categories(:general).id)
authors = Author.joins(:essay_categories).where("categories.id" => categories(:general).id)
assert_equal authors(:david), authors.first
assert_equal [owners(:blackbeard)], authors(:david).essay_owners
@ -944,7 +944,7 @@ def test_has_many_through_polymorphic_with_primary_key_option
def test_has_many_through_with_primary_key_option
assert_equal [categories(:general)], authors(:david).essay_categories_2
authors = Author.joins(:essay_categories_2).where('categories.id' => categories(:general).id)
authors = Author.joins(:essay_categories_2).where("categories.id" => categories(:general).id)
assert_equal authors(:david), authors.first
end
@ -956,7 +956,7 @@ def test_size_of_through_association_should_increase_correctly_when_has_many_ass
end
def test_has_many_through_with_default_scope_on_join_model
assert_equal posts(:welcome).comments.order('id').to_a, authors(:david).comments_on_first_posts
assert_equal posts(:welcome).comments.order("id").to_a, authors(:david).comments_on_first_posts
end
def test_create_has_many_through_with_default_scope_on_join_model
@ -971,15 +971,15 @@ def test_joining_has_many_through_with_distinct
end
def test_joining_has_many_through_belongs_to
posts = Post.joins(:author_categorizations).order('posts.id').
where('categorizations.id' => categorizations(:mary_thinking_sti).id)
posts = Post.joins(:author_categorizations).order("posts.id").
where("categorizations.id" => categorizations(:mary_thinking_sti).id)
assert_equal [posts(:eager_other), posts(:misc_by_mary), posts(:other_by_mary)], posts
end
def test_select_chosen_fields_only
author = authors(:david)
assert_equal ['body', 'id'].sort, author.comments.select('comments.body').first.attributes.keys.sort
assert_equal ["body", "id"].sort, author.comments.select("comments.body").first.attributes.keys.sort
end
def test_get_has_many_through_belongs_to_ids_with_conditions
@ -1039,29 +1039,29 @@ 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])
Categorization.validate { |r| r.errors[:base] << "Invalid Categorization" }
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
def test_create_bang_should_raise_exception_when_join_record_has_errors
repair_validations(Categorization) do
Categorization.validate { |r| r.errors[:base] << 'Invalid Categorization' }
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
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])
Categorization.validate { |r| r.errors[:base] << "Invalid Categorization" }
c = Category.new(:name => "Fishing", :authors => [Author.first])
assert_raises(ActiveRecord::RecordInvalid) do
c.save!
end
@ -1070,17 +1070,17 @@ 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])
Categorization.validate { |r| r.errors[:base] << "Invalid Categorization" }
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.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 person.posts.loaded?, "person.posts should be loaded"
assert_equal [], person.posts
end
@ -1116,7 +1116,7 @@ def test_has_many_through_associations_on_new_records_use_null_relations
assert_no_queries(ignore_none: false) do
assert_equal [], person.posts
assert_equal [], person.posts.where(body: 'omg')
assert_equal [], person.posts.where(body: "omg")
assert_equal [], person.posts.pluck(:body)
assert_equal 0, person.posts.sum(:tags_count)
assert_equal 0, person.posts.count
@ -1148,7 +1148,7 @@ 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!")
post = Post.create!(:title => "Beaches", :body => "I like beaches!")
Reader.create! :person => people(:david), :post => post
LazyReader.create! :person => people(:susan), :post => post
@ -1160,8 +1160,8 @@ def test_has_many_through_unscope_default_scope
end
def test_has_many_through_add_with_sti_middle_relation
club = SuperClub.create!(name: 'Fight Club')
member = Member.create!(name: 'Tyler Durden')
club = SuperClub.create!(name: "Fight Club")
member = Member.create!(name: "Tyler Durden")
club.members << member
assert_equal 1, SuperMembership.where(member_id: member.id, club_id: club.id).count

@ -1,15 +1,15 @@
require "cases/helper"
require 'models/developer'
require 'models/computer'
require 'models/project'
require 'models/company'
require 'models/ship'
require 'models/pirate'
require 'models/car'
require 'models/bulb'
require 'models/author'
require 'models/image'
require 'models/post'
require "models/developer"
require "models/computer"
require "models/project"
require "models/company"
require "models/ship"
require "models/pirate"
require "models/car"
require "models/bulb"
require "models/author"
require "models/image"
require "models/post"
class HasOneAssociationsTest < ActiveRecord::TestCase
self.use_transactional_tests = false unless supports_savepoints?
@ -28,7 +28,7 @@ def test_has_one_does_not_use_order_by
ActiveRecord::SQLCounter.clear_log
companies(:first_firm).account
ensure
assert ActiveRecord::SQLCounter.log_all.all? { |sql| /order by/i !~ sql }, 'ORDER BY was used in the query'
assert ActiveRecord::SQLCounter.log_all.all? { |sql| /order by/i !~ sql }, "ORDER BY was used in the query"
end
def test_has_one_cache_nils
@ -170,27 +170,27 @@ 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 = 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
def test_restrict_with_error_is_deprecated_using_key_one
I18n.backend = I18n::Backend::Simple.new
I18n.backend.store_translations :en, activerecord: { errors: { messages: { restrict_dependent_destroy: { one: 'message for deprecated key' } } } }
I18n.backend.store_translations :en, activerecord: { errors: { messages: { restrict_dependent_destroy: { one: "message for deprecated key" } } } }
firm = RestrictedWithErrorFirm.create!(name: 'restrict')
firm = RestrictedWithErrorFirm.create!(name: "restrict")
firm.create_account(credit_limit: 10)
assert_not_nil firm.account
@ -198,15 +198,15 @@ def test_restrict_with_error_is_deprecated_using_key_one
assert_deprecated { firm.destroy }
assert !firm.errors.empty?
assert_equal 'message for deprecated key', firm.errors[:base].first
assert RestrictedWithErrorFirm.exists?(name: 'restrict')
assert_equal "message for deprecated key", firm.errors[:base].first
assert RestrictedWithErrorFirm.exists?(name: "restrict")
assert firm.account.present?
ensure
I18n.backend.reload!
end
def test_restrict_with_error
firm = RestrictedWithErrorFirm.create!(:name => 'restrict')
firm = RestrictedWithErrorFirm.create!(:name => "restrict")
firm.create_account(:credit_limit => 10)
assert_not_nil firm.account
@ -215,14 +215,14 @@ 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
def test_restrict_with_error_with_locale
I18n.backend = I18n::Backend::Simple.new
I18n.backend.store_translations 'en', activerecord: {attributes: {restricted_with_error_firm: {account: 'firm account'}}}
firm = RestrictedWithErrorFirm.create!(name: 'restrict')
I18n.backend.store_translations "en", activerecord: {attributes: {restricted_with_error_firm: {account: "firm account"}}}
firm = RestrictedWithErrorFirm.create!(name: "restrict")
firm.create_account(credit_limit: 10)
assert_not_nil firm.account
@ -231,7 +231,7 @@ def test_restrict_with_error_with_locale
assert !firm.errors.empty?
assert_equal "Cannot delete record because a dependent firm account exists", firm.errors[:base].first
assert RestrictedWithErrorFirm.exists?(name: 'restrict')
assert RestrictedWithErrorFirm.exists?(name: "restrict")
assert firm.account.present?
ensure
I18n.backend.reload!
@ -319,7 +319,7 @@ def test_create_association_with_bang_failing
end
def test_create_with_inexistent_foreign_key_failing
firm = Firm.create(name: 'GlobalMegaCorp')
firm = Firm.create(name: "GlobalMegaCorp")
assert_raises(ActiveRecord::UnknownAttributeError) do
firm.create_account_with_inexistent_foreign_key
@ -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
@ -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,7 +505,7 @@ 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
@ -537,31 +537,31 @@ def test_association_protect_foreign_key
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
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
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
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']
assert_equal car.id, bulb.attributes_after_initialize["car_id"]
end
def test_has_one_transaction
@ -581,36 +581,36 @@ def test_has_one_transaction
def test_has_one_assignment_dont_trigger_save_on_change_of_same_object
pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?")
ship = pirate.build_ship(name: 'old name')
ship = pirate.build_ship(name: "old name")
ship.save!
ship.name = 'new name'
ship.name = "new name"
assert ship.changed?
assert_queries(1) do
# One query for updating name, not triggering query for updating pirate_id
pirate.ship = ship
end
assert_equal 'new name', pirate.ship.reload.name
assert_equal "new name", pirate.ship.reload.name
end
def test_has_one_assignment_triggers_save_on_change_on_replacing_object
pirate = Pirate.create!(catchphrase: "Don' botharrr talkin' like one, savvy?")
ship = pirate.build_ship(name: 'old name')
ship = pirate.build_ship(name: "old name")
ship.save!
new_ship = Ship.create(name: 'new name')
new_ship = Ship.create(name: "new name")
assert_queries(2) do
# One query for updating name and second query for updating pirate_id
pirate.ship = new_ship
end
assert_equal 'new name', pirate.ship.reload.name
assert_equal "new name", pirate.ship.reload.name
end
def test_has_one_autosave_with_primary_key_manually_set
post = Post.create(id: 1234, title: "Some title", body: 'Some content')
author = Author.new(id: 33, name: 'Hank Moody')
post = Post.create(id: 1234, title: "Some title", body: "Some content")
author = Author.new(id: 33, name: "Hank Moody")
author.post = post
author.save
@ -621,7 +621,7 @@ def test_has_one_autosave_with_primary_key_manually_set
end
def test_has_one_loading_for_new_record
post = Post.create!(author_id: 42, title: 'foo', body: 'bar')
post = Post.create!(author_id: 42, title: "foo", body: "bar")
author = Author.new(id: 42)
assert_equal post, author.post
end
@ -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
@ -644,8 +644,8 @@ def test_with_polymorphic_has_one_with_custom_columns_name
assert_equal image, post.main_image
end
test 'dangerous association name raises ArgumentError' do
[:errors, 'errors', :save, 'save'].each do |name|
test "dangerous association name raises ArgumentError" do
[:errors, "errors", :save, "save"].each do |name|
assert_raises(ArgumentError, "Association #{name} should not be allowed") do
Class.new(ActiveRecord::Base) do
has_one name
@ -661,20 +661,20 @@ def test_association_force_reload_with_only_true_is_deprecated
end
class SpecialBook < ActiveRecord::Base
self.table_name = 'books'
belongs_to :author, class_name: 'SpecialAuthor'
self.table_name = "books"
belongs_to :author, class_name: "SpecialAuthor"
end
class SpecialAuthor < ActiveRecord::Base
self.table_name = 'authors'
has_one :book, class_name: 'SpecialBook', foreign_key: 'author_id'
self.table_name = "authors"
has_one :book, class_name: "SpecialBook", foreign_key: "author_id"
end
def test_assocation_enum_works_properly
author = SpecialAuthor.create!(name: 'Test')
book = SpecialBook.create!(status: 'published')
author = SpecialAuthor.create!(name: "Test")
book = SpecialBook.create!(status: "published")
author.book = book
refute_equal 0, SpecialAuthor.joins(:book).where(books: { status: 'published' } ).count
refute_equal 0, SpecialAuthor.joins(:book).where(books: { status: "published" } ).count
end
end

@ -1,25 +1,25 @@
require "cases/helper"
require 'models/club'
require 'models/member_type'
require 'models/member'
require 'models/membership'
require 'models/sponsor'
require 'models/organization'
require 'models/member_detail'
require 'models/minivan'
require 'models/dashboard'
require 'models/speedometer'
require 'models/category'
require 'models/author'
require 'models/essay'
require 'models/owner'
require 'models/post'
require 'models/comment'
require 'models/categorization'
require 'models/customer'
require 'models/carrier'
require 'models/shop_account'
require 'models/customer_carrier'
require "models/club"
require "models/member_type"
require "models/member"
require "models/membership"
require "models/sponsor"
require "models/organization"
require "models/member_detail"
require "models/minivan"
require "models/dashboard"
require "models/speedometer"
require "models/category"
require "models/author"
require "models/essay"
require "models/owner"
require "models/post"
require "models/comment"
require "models/categorization"
require "models/customer"
require "models/carrier"
require "models/shop_account"
require "models/customer_carrier"
class HasOneThroughAssociationsTest < ActiveRecord::TestCase
fixtures :member_types, :members, :clubs, :memberships, :sponsors, :organizations, :minivans,
@ -51,8 +51,8 @@ def test_creating_association_builds_through_record_for_new
end
def test_creating_association_sets_both_parent_ids_for_new
member = Member.new(name: 'Sean Griffin')
club = Club.new(name: 'Da Club')
member = Member.new(name: "Sean Griffin")
club = Club.new(name: "Da Club")
member.club = club
@ -130,7 +130,7 @@ def test_eager_has_one_through_polymorphic_with_source_type
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,7 +138,7 @@ 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}
@ -147,7 +147,7 @@ def test_has_one_through_nonpreload_eager_loading_through_polymorphic
def test_has_one_through_nonpreload_eager_loading_through_polymorphic_with_more_than_one_through_record
Sponsor.new(:sponsor_club => clubs(:crazy_club), :sponsorable => members(:groucho)).save!
members = assert_queries(1) do
Member.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 }
@ -176,35 +176,35 @@ 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')
assert_difference "MemberDetail.count", 1 do
@member_detail = MemberDetail.new(:extra_data => "Extra")
@member.member_detail = @member_detail
@member.organization = @organization
end
assert_equal @organization, @member.organization
assert @organization.members.include?(@member)
assert_equal 'Extra', @member.member_detail.extra_data
assert_equal "Extra", @member.member_detail.extra_data
end
def test_reassigning_has_one_through
@organization = organizations(:nsa)
@new_organization = organizations(:discordians)
assert_difference 'MemberDetail.count', 1 do
@member_detail = MemberDetail.new(:extra_data => 'Extra')
assert_difference "MemberDetail.count", 1 do
@member_detail = MemberDetail.new(:extra_data => "Extra")
@member.member_detail = @member_detail
@member.organization = @organization
end
assert_equal @organization, @member.organization
assert_equal 'Extra', @member.member_detail.extra_data
assert_equal "Extra", @member.member_detail.extra_data
assert @organization.members.include?(@member)
assert !@new_organization.members.include?(@member)
assert_no_difference 'MemberDetail.count' do
assert_no_difference "MemberDetail.count" do
@member.organization = @new_organization
end
assert_equal @new_organization, @member.organization
assert_equal 'Extra', @member.member_detail.extra_data
assert_equal "Extra", @member.member_detail.extra_data
assert !@organization.members.include?(@member)
assert @new_organization.members.include?(@member)
end
@ -242,7 +242,7 @@ def test_save_of_record_with_loaded_has_one_through
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!
@ -261,7 +261,7 @@ def test_through_belongs_to_after_destroy
end
def test_value_is_properly_quoted
minivan = Minivan.find('m1')
minivan = Minivan.find("m1")
assert_nothing_raised do
minivan.dashboard
end
@ -270,7 +270,7 @@ def test_value_is_properly_quoted
def test_has_one_through_polymorphic_with_primary_key_option
assert_equal categories(:general), authors(:david).essay_category
authors = Author.joins(:essay_category).where('categories.id' => categories(:general).id)
authors = Author.joins(:essay_category).where("categories.id" => categories(:general).id)
assert_equal authors(:david), authors.first
assert_equal owners(:blackbeard), authors(:david).essay_owner
@ -282,12 +282,12 @@ def test_has_one_through_polymorphic_with_primary_key_option
def test_has_one_through_with_primary_key_option
assert_equal categories(:general), authors(:david).essay_category_2
authors = Author.joins(:essay_category_2).where('categories.id' => categories(:general).id)
authors = Author.joins(:essay_category_2).where("categories.id" => categories(:general).id)
assert_equal authors(:david), authors.first
end
def test_has_one_through_with_default_scope_on_join_model
assert_equal posts(:welcome).comments.order('id').first, authors(:david).comment_on_first_post
assert_equal posts(:welcome).comments.order("id").first, authors(:david).comment_on_first_post
end
def test_has_one_through_many_raises_exception

@ -1,13 +1,13 @@
require "cases/helper"
require 'models/post'
require 'models/comment'
require 'models/author'
require 'models/essay'
require 'models/category'
require 'models/categorization'
require 'models/person'
require 'models/tagging'
require 'models/tag'
require "models/post"
require "models/comment"
require "models/author"
require "models/essay"
require "models/category"
require "models/categorization"
require "models/person"
require "models/tagging"
require "models/tag"
class InnerJoinAssociationTest < ActiveRecord::TestCase
fixtures :authors, :essays, :posts, :comments, :categories, :categories_posts, :categorizations,
@ -58,7 +58,7 @@ def test_find_with_implicit_inner_joins_without_select_does_not_imply_readonly
end
def test_find_with_implicit_inner_joins_honors_readonly_with_select
authors = Author.joins(:posts).select('authors.*').to_a
authors = Author.joins(:posts).select("authors.*").to_a
assert !authors.empty?, "expected authors to be non-empty"
assert authors.all? {|a| !a.readonly? }, "expected no authors to be readonly"
end
@ -70,7 +70,7 @@ def test_find_with_implicit_inner_joins_honors_readonly_false
end
def test_find_with_implicit_inner_joins_does_not_set_associations
authors = Author.joins(:posts).select('authors.*').to_a
authors = Author.joins(:posts).select("authors.*").to_a
assert !authors.empty?, "expected authors to be non-empty"
assert authors.all? { |a| !a.instance_variable_defined?(:@posts) }, "expected no authors to have the @posts association loaded"
end
@ -82,12 +82,12 @@ def test_count_honors_implicit_inner_joins
def test_calculate_honors_implicit_inner_joins
real_count = Author.all.to_a.sum{|a| a.posts.count }
assert_equal real_count, Author.joins(:posts).calculate(:count, 'authors.id'), "plain inner join count should match the number of referenced posts records"
assert_equal real_count, Author.joins(:posts).calculate(:count, "authors.id"), "plain inner join count should match the number of referenced posts records"
end
def test_calculate_honors_implicit_inner_joins_and_distinct_and_conditions
real_count = Author.all.to_a.select {|a| a.posts.any? {|p| p.title.start_with?('Welcome')} }.length
authors_with_welcoming_post_titles = Author.all.merge!(joins: :posts, where: "posts.title like 'Welcome%'").distinct.calculate(:count, 'authors.id')
real_count = Author.all.to_a.select {|a| a.posts.any? {|p| p.title.start_with?("Welcome")} }.length
authors_with_welcoming_post_titles = Author.all.merge!(joins: :posts, where: "posts.title like 'Welcome%'").distinct.calculate(:count, "authors.id")
assert_equal real_count, authors_with_welcoming_post_titles, "inner join and conditions should have only returned authors posting titles starting with 'Welcome'"
end
@ -120,8 +120,8 @@ def test_find_with_conditions_on_through_reflection
test "the default scope of the target is correctly aliased when joining associations" do
author = Author.create! name: "Jon"
author.categories.create! name: 'Not Special'
author.special_categories.create! name: 'Special'
author.categories.create! name: "Not Special"
author.special_categories.create! name: "Special"
categories = author.categories.includes(:special_categorizations).references(:special_categorizations).to_a
assert_equal 2, categories.size
@ -129,8 +129,8 @@ def test_find_with_conditions_on_through_reflection
test "the correct records are loaded when including an aliased association" do
author = Author.create! name: "Jon"
author.categories.create! name: 'Not Special'
author.special_categories.create! name: 'Special'
author.categories.create! name: "Not Special"
author.special_categories.create! name: "Special"
categories = author.categories.eager_load(:special_categorizations).order(:name).to_a
assert_equal 0, categories.first.special_categorizations.size

@ -1,21 +1,21 @@
require "cases/helper"
require 'models/man'
require 'models/face'
require 'models/interest'
require 'models/zine'
require 'models/club'
require 'models/sponsor'
require 'models/rating'
require 'models/comment'
require 'models/car'
require 'models/bulb'
require 'models/mixed_case_monkey'
require 'models/admin'
require 'models/admin/account'
require 'models/admin/user'
require 'models/developer'
require 'models/company'
require 'models/project'
require "models/man"
require "models/face"
require "models/interest"
require "models/zine"
require "models/club"
require "models/sponsor"
require "models/rating"
require "models/comment"
require "models/car"
require "models/bulb"
require "models/mixed_case_monkey"
require "models/admin"
require "models/admin/account"
require "models/admin/user"
require "models/developer"
require "models/company"
require "models/project"
class AutomaticInverseFindingTests < ActiveRecord::TestCase
fixtures :ratings, :comments, :cars
@ -203,9 +203,9 @@ def test_associations_with_no_inverse_of_should_return_nil
end
def test_this_inverse_stuff
firm = Firm.create!(name: 'Adequate Holdings')
Project.create!(name: 'Project 1', firm: firm)
Developer.create!(name: 'Gorbypuff', firm: firm)
firm = Firm.create!(name: "Adequate Holdings")
Project.create!(name: "Project 1", firm: firm)
Developer.create!(name: "Gorbypuff", firm: firm)
new_project = Project.last
assert Project.reflect_on_association(:lead_developer).inverse_of.present?, "Expected inverse of to be present"
@ -220,73 +220,73 @@ def test_parent_instance_should_be_shared_with_child_on_find
m = men(:gordon)
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'
m.name = "Bongo"
assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
f.man.name = 'Mungo'
f.man.name = "Mungo"
assert_equal m.name, f.man.name, "Name of man should be the same after changes to child-owned instance"
end
def test_parent_instance_should_be_shared_with_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'
m.name = "Bongo"
assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
f.man.name = 'Mungo'
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'
m.name = "Bongo"
assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
f.man.name = 'Mungo'
f.man.name = "Mungo"
assert_equal m.name, f.man.name, "Name of man should be the same after changes to child-owned instance"
end
def test_parent_instance_should_be_shared_with_newly_built_child
m = 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'
m.name = "Bongo"
assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
f.man.name = 'Mungo'
f.man.name = "Mungo"
assert_equal m.name, f.man.name, "Name of man should be the same after changes to just-built-child-owned instance"
end
def test_parent_instance_should_be_shared_with_newly_created_child
m = 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'
m.name = "Bongo"
assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
f.man.name = 'Mungo'
f.man.name = "Mungo"
assert_equal m.name, f.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
end
def test_parent_instance_should_be_shared_with_newly_created_child_via_bang_method
m = Man.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'
m.name = "Bongo"
assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
f.man.name = 'Mungo'
f.man.name = "Mungo"
assert_equal m.name, f.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
end
def test_parent_instance_should_be_shared_with_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"
m.name = 'Bongo'
m.name = "Bongo"
assert_equal m.name, f.man.name, "Name of man should be the same after changes to parent instance"
f.man.name = 'Mungo'
f.man.name = "Mungo"
assert_equal m.name, f.man.name, "Name of man should be the same after changes to replaced-child-owned instance"
end
@ -303,67 +303,67 @@ def test_parent_instance_should_be_shared_with_every_child_on_find
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"
m.name = 'Bongo'
m.name = "Bongo"
assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
i.man.name = 'Mungo'
i.man.name = "Mungo"
assert_equal m.name, i.man.name, "Name of man should be the same after changes to child-owned instance"
end
end
def test_parent_instance_should_be_shared_with_eager_loaded_children
m = 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"
m.name = 'Bongo'
m.name = "Bongo"
assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
i.man.name = 'Mungo'
i.man.name = "Mungo"
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"
m.name = 'Bongo'
m.name = "Bongo"
assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
i.man.name = 'Mungo'
i.man.name = "Mungo"
assert_equal m.name, i.man.name, "Name of man should be the same after changes to child-owned instance"
end
end
def test_parent_instance_should_be_shared_with_newly_block_style_built_child
m = Man.first
i = m.interests.build {|ii| ii.topic = 'Industrial Revolution Re-enactment'}
i = m.interests.build {|ii| ii.topic = "Industrial Revolution Re-enactment"}
assert_not_nil i.topic, "Child attributes supplied to build via blocks should be populated"
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'
m.name = "Bongo"
assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
i.man.name = 'Mungo'
i.man.name = "Mungo"
assert_equal m.name, i.man.name, "Name of man should be the same after changes to just-built-child-owned instance"
end
def test_parent_instance_should_be_shared_with_newly_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'
m.name = "Bongo"
assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
i.man.name = 'Mungo'
i.man.name = "Mungo"
assert_equal m.name, i.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
end
def test_parent_instance_should_be_shared_with_newly_block_style_created_child
m = Man.first
i = m.interests.create {|ii| ii.topic = 'Industrial Revolution Re-enactment'}
i = m.interests.create {|ii| ii.topic = "Industrial Revolution Re-enactment"}
assert_not_nil i.topic, "Child attributes supplied to create via blocks should be populated"
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'
m.name = "Bongo"
assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
i.man.name = 'Mungo'
i.man.name = "Mungo"
assert_equal m.name, i.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
end
@ -385,25 +385,25 @@ 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"
m.name = 'Bongo'
m.name = "Bongo"
assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
i.man.name = 'Mungo'
i.man.name = "Mungo"
assert_equal m.name, i.man.name, "Name of man should be the same after changes to newly-created-child-owned instance"
end
def test_parent_instance_should_be_shared_with_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"
m.name = 'Bongo'
m.name = "Bongo"
assert_equal m.name, i.man.name, "Name of man should be the same after changes to parent instance"
i.man.name = 'Mungo'
i.man.name = "Mungo"
assert_equal m.name, i.man.name, "Name of man should be the same after changes to replaced-child-owned instance"
end
@ -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
@ -504,49 +504,49 @@ def test_child_instance_should_be_shared_with_parent_on_find
f = faces(:trusting)
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'
f.description = "gormless"
assert_equal f.description, m.face.description, "Description of face should be the same after changes to child instance"
m.face.description = 'pleasing'
m.face.description = "pleasing"
assert_equal f.description, m.face.description, "Description of face should be the same after changes to parent-owned instance"
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'
f.description = "gormless"
assert_equal f.description, m.face.description, "Description of face should be the same after changes to child instance"
m.face.description = 'pleasing'
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'
f.description = "gormless"
assert_equal f.description, m.face.description, "Description of face should be the same after changes to child instance"
m.face.description = 'pleasing'
m.face.description = "pleasing"
assert_equal f.description, m.face.description, "Description of face should be the same after changes to parent-owned instance"
end
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'
f.description = "gormless"
assert_equal f.description, m.face.description, "Description of face should be the same after changes to child instance"
m.face.description = 'pleasing'
m.face.description = "pleasing"
assert_equal f.description, m.face.description, "Description of face should be the same after changes to just-built-parent-owned instance"
end
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'
f.description = "gormless"
assert_equal f.description, m.face.description, "Description of face should be the same after changes to child instance"
m.face.description = 'pleasing'
m.face.description = "pleasing"
assert_equal f.description, m.face.description, "Description of face should be the same after changes to newly-created-parent-owned instance"
end
@ -557,21 +557,21 @@ def test_should_not_try_to_set_inverse_instances_when_the_inverse_is_a_has_many
iz = m.interests.detect { |_iz| _iz.id == i.id}
assert_not_nil iz
assert_equal i.topic, iz.topic, "Interest topics should be the same before changes to child"
i.topic = 'Eating cheese with a spoon'
i.topic = "Eating cheese with a spoon"
assert_not_equal i.topic, iz.topic, "Interest topics should not be the same after changes to child"
iz.topic = 'Cow tipping'
iz.topic = "Cow tipping"
assert_not_equal i.topic, iz.topic, "Interest topics should not be the same after changes to parent-owned instance"
end
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"
f.description = 'gormless'
f.description = "gormless"
assert_equal f.description, m.face.description, "Description of face should be the same after changes to child instance"
m.face.description = 'pleasing'
m.face.description = "pleasing"
assert_equal f.description, m.face.description, "Description of face should be the same after changes to replaced-parent-owned instance"
end
@ -584,30 +584,30 @@ 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'
f.description = "gormless"
assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to child instance"
m.polymorphic_face.description = 'pleasing'
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"
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'
f.description = "gormless"
assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to child instance"
m.polymorphic_face.description = 'pleasing'
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'
f.description = "gormless"
assert_equal f.description, m.polymorphic_face.description, "Description of face should be the same after changes to child instance"
m.polymorphic_face.description = 'pleasing'
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"
end
@ -619,9 +619,9 @@ def test_child_instance_should_be_shared_with_replaced_via_accessor_parent
face.polymorphic_man = new_man
assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same before changes to parent instance"
face.description = 'Bongo'
face.description = "Bongo"
assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same after changes to parent instance"
new_man.polymorphic_face.description = 'Mungo'
new_man.polymorphic_face.description = "Mungo"
assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same after changes to replaced-parent-owned instance"
end
@ -633,9 +633,9 @@ def test_child_instance_should_be_shared_with_replaced_via_method_parent
face.polymorphic_man = new_man
assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same before changes to parent instance"
face.description = 'Bongo'
face.description = "Bongo"
assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same after changes to parent instance"
new_man.polymorphic_face.description = 'Mungo'
new_man.polymorphic_face.description = "Mungo"
assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same after changes to replaced-parent-owned instance"
end
@ -658,9 +658,9 @@ def test_should_not_try_to_set_inverse_instances_when_the_inverse_is_a_has_many
iz = m.polymorphic_interests.detect { |_iz| _iz.id == i.id}
assert_not_nil iz
assert_equal i.topic, iz.topic, "Interest topics should be the same before changes to child"
i.topic = 'Eating cheese with a spoon'
i.topic = "Eating cheese with a spoon"
assert_not_equal i.topic, iz.topic, "Interest topics should not be the same after changes to child"
iz.topic = 'Cow tipping'
iz.topic = "Cow tipping"
assert_not_equal i.topic, iz.topic, "Interest topics should not be the same after changes to parent-owned instance"
end
@ -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

@ -1,20 +1,20 @@
require "cases/helper"
require 'models/tag'
require 'models/tagging'
require 'models/post'
require 'models/rating'
require 'models/item'
require 'models/comment'
require 'models/author'
require 'models/category'
require 'models/categorization'
require 'models/vertex'
require 'models/edge'
require 'models/book'
require 'models/citation'
require 'models/aircraft'
require 'models/engine'
require 'models/car'
require "models/tag"
require "models/tagging"
require "models/post"
require "models/rating"
require "models/item"
require "models/comment"
require "models/author"
require "models/category"
require "models/categorization"
require "models/vertex"
require "models/edge"
require "models/book"
require "models/citation"
require "models/aircraft"
require "models/engine"
require "models/car"
class AssociationsJoinModelTest < ActiveRecord::TestCase
self.use_transactional_tests = false unless supports_savepoints?
@ -97,7 +97,7 @@ 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)
@ -174,7 +174,7 @@ def test_create_polymorphic_has_one_with_scope
def test_delete_polymorphic_has_many_with_delete_all
assert_equal 1, posts(:welcome).taggings.count
posts(:welcome).taggings.first.update_columns taggable_type: 'PostWithHasManyDeleteAll'
posts(:welcome).taggings.first.update_columns taggable_type: "PostWithHasManyDeleteAll"
post = find_post_with_dependency(1, :has_many, :taggings, :delete_all)
old_count = Tagging.count
@ -185,7 +185,7 @@ def test_delete_polymorphic_has_many_with_delete_all
def test_delete_polymorphic_has_many_with_destroy
assert_equal 1, posts(:welcome).taggings.count
posts(:welcome).taggings.first.update_columns taggable_type: 'PostWithHasManyDestroy'
posts(:welcome).taggings.first.update_columns taggable_type: "PostWithHasManyDestroy"
post = find_post_with_dependency(1, :has_many, :taggings, :destroy)
old_count = Tagging.count
@ -196,7 +196,7 @@ def test_delete_polymorphic_has_many_with_destroy
def test_delete_polymorphic_has_many_with_nullify
assert_equal 1, posts(:welcome).taggings.count
posts(:welcome).taggings.first.update_columns taggable_type: 'PostWithHasManyNullify'
posts(:welcome).taggings.first.update_columns taggable_type: "PostWithHasManyNullify"
post = find_post_with_dependency(1, :has_many, :taggings, :nullify)
old_count = Tagging.count
@ -207,7 +207,7 @@ def test_delete_polymorphic_has_many_with_nullify
def test_delete_polymorphic_has_one_with_destroy
assert posts(:welcome).tagging
posts(:welcome).tagging.update_columns taggable_type: 'PostWithHasOneDestroy'
posts(:welcome).tagging.update_columns taggable_type: "PostWithHasOneDestroy"
post = find_post_with_dependency(1, :has_one, :tagging, :destroy)
old_count = Tagging.count
@ -219,7 +219,7 @@ def test_delete_polymorphic_has_one_with_destroy
def test_delete_polymorphic_has_one_with_nullify
assert posts(:welcome).tagging
posts(:welcome).tagging.update_columns taggable_type: 'PostWithHasOneNullify'
posts(:welcome).tagging.update_columns taggable_type: "PostWithHasOneNullify"
post = find_post_with_dependency(1, :has_one, :tagging, :nullify)
old_count = Tagging.count
@ -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'}
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 }
@ -302,7 +302,7 @@ def test_has_many_find_conditions
end
def test_has_many_array_methods_called_by_method_missing
assert authors(:david).categories.any? { |category| category.name == 'General' }
assert authors(:david).categories.any? { |category| category.name == "General" }
assert_nothing_raised { authors(:david).categories.sort }
end
@ -324,7 +324,7 @@ def test_has_many_through_with_custom_primary_key_on_belongs_to_source
end
def test_has_many_through_with_custom_primary_key_on_has_many_source
assert_equal [authors(:david), authors(:bob)], posts(:thinking).authors_using_custom_pk.order('authors.id')
assert_equal [authors(:david), authors(:bob)], posts(:thinking).authors_using_custom_pk.order("authors.id")
end
def test_belongs_to_polymorphic_with_counter_cache
@ -354,7 +354,7 @@ def test_has_many_polymorphic
end
assert_raise ActiveRecord::EagerLoadPolymorphicError do
tags(:general).taggings.includes(:taggable).where('bogus_table.column = 1').references(:bogus_table).to_a
tags(:general).taggings.includes(:taggable).where("bogus_table.column = 1").references(:bogus_table).to_a
end
end
@ -365,7 +365,7 @@ 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
@ -381,19 +381,19 @@ def test_eager_has_many_polymorphic_with_source_type
end
def test_has_many_through_has_many_find_all
assert_equal comments(:greetings), authors(:david).comments.order('comments.id').to_a.first
assert_equal comments(:greetings), authors(:david).comments.order("comments.id").to_a.first
end
def test_has_many_through_has_many_find_all_with_custom_class
assert_equal comments(:greetings), authors(:david).funky_comments.order('comments.id').to_a.first
assert_equal comments(:greetings), authors(:david).funky_comments.order("comments.id").to_a.first
end
def test_has_many_through_has_many_find_first
assert_equal comments(:greetings), authors(:david).comments.order('comments.id').first
assert_equal comments(:greetings), authors(:david).comments.order("comments.id").first
end
def test_has_many_through_has_many_find_conditions
options = { :where => "comments.#{QUOTED_TYPE}='SpecialComment'", :order => 'comments.id' }
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)
@ -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)
@ -601,7 +601,7 @@ def test_deleting_junk_from_has_many_through_should_raise_type_mismatch
def test_deleting_by_integer_id_from_has_many_through
post = posts(:thinking)
assert_difference 'post.tags.count', -1 do
assert_difference "post.tags.count", -1 do
assert_equal 1, post.tags.delete(1).size
end
@ -611,8 +611,8 @@ def test_deleting_by_integer_id_from_has_many_through
def test_deleting_by_string_id_from_has_many_through
post = posts(:thinking)
assert_difference 'post.tags.count', -1 do
assert_equal 1, post.tags.delete('1').size
assert_difference "post.tags.count", -1 do
assert_equal 1, post.tags.delete("1").size
end
assert_equal 0, post.tags.size
@ -660,8 +660,8 @@ def test_polymorphic_belongs_to
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,15 +728,15 @@ 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
@ -749,17 +749,17 @@ def test_has_many_with_pluralize_table_names_false
def test_proper_error_message_for_eager_load_and_includes_association_errors
includes_error = assert_raises(ActiveRecord::ConfigurationError) {
Post.includes(:nonexistent_relation).where(nonexistent_relation: {name: 'Rochester'}).find(1)
Post.includes(:nonexistent_relation).where(nonexistent_relation: {name: "Rochester"}).find(1)
}
assert_equal("Can't join 'Post' to association named 'nonexistent_relation'; perhaps you misspelled it?", includes_error.message)
eager_load_error = assert_raises(ActiveRecord::ConfigurationError) {
Post.eager_load(:nonexistent_relation).where(nonexistent_relation: {name: 'Rochester'}).find(1)
Post.eager_load(:nonexistent_relation).where(nonexistent_relation: {name: "Rochester"}).find(1)
}
assert_equal("Can't join 'Post' to association named 'nonexistent_relation'; perhaps you misspelled it?", eager_load_error.message)
includes_and_eager_load_error = assert_raises(ActiveRecord::ConfigurationError) {
Post.eager_load(:nonexistent_relation).includes(:nonexistent_relation).where(nonexistent_relation: {name: 'Rochester'}).find(1)
Post.eager_load(:nonexistent_relation).includes(:nonexistent_relation).where(nonexistent_relation: {name: "Rochester"}).find(1)
}
assert_equal("Can't join 'Post' to association named 'nonexistent_relation'; perhaps you misspelled it?", includes_and_eager_load_error.message)
end
@ -770,7 +770,7 @@ def find_post_with_dependency(post_id, association, association_name, dependency
class_name = "PostWith#{association.to_s.classify}#{dependency.to_s.classify}"
Post.find(post_id).update_columns type: class_name
klass = Object.const_set(class_name, Class.new(ActiveRecord::Base))
klass.table_name = 'posts'
klass.table_name = "posts"
klass.send(association, association_name, :as => :taggable, :dependent => dependency)
klass.find(post_id)
end

@ -1,11 +1,11 @@
require "cases/helper"
require 'models/post'
require 'models/comment'
require 'models/author'
require 'models/essay'
require 'models/categorization'
require 'models/person'
require 'active_support/core_ext/regexp'
require "models/post"
require "models/comment"
require "models/author"
require "models/essay"
require "models/categorization"
require "models/person"
require "active_support/core_ext/regexp"
class LeftOuterJoinAssociationTest < ActiveRecord::TestCase
fixtures :authors, :essays, :posts, :comments, :categorizations, :people

@ -1,27 +1,27 @@
require "cases/helper"
require 'models/author'
require 'models/post'
require 'models/person'
require 'models/reference'
require 'models/job'
require 'models/reader'
require 'models/comment'
require 'models/tag'
require 'models/tagging'
require 'models/subscriber'
require 'models/book'
require 'models/subscription'
require 'models/rating'
require 'models/member'
require 'models/member_detail'
require 'models/member_type'
require 'models/sponsor'
require 'models/club'
require 'models/organization'
require 'models/category'
require 'models/categorization'
require 'models/membership'
require 'models/essay'
require "models/author"
require "models/post"
require "models/person"
require "models/reference"
require "models/job"
require "models/reader"
require "models/comment"
require "models/tag"
require "models/tagging"
require "models/subscriber"
require "models/book"
require "models/subscription"
require "models/rating"
require "models/member"
require "models/member_detail"
require "models/member_type"
require "models/sponsor"
require "models/club"
require "models/organization"
require "models/category"
require "models/categorization"
require "models/membership"
require "models/essay"
class NestedThroughAssociationsTest < ActiveRecord::TestCase
fixtures :authors, :books, :posts, :subscriptions, :subscribers, :tags, :taggings,
@ -65,12 +65,12 @@ def test_has_many_through_has_many_with_has_many_through_source_reflection_prelo
def test_has_many_through_has_many_with_has_many_through_source_reflection_preload_via_joins
assert_includes_and_joins_equal(
Author.where('tags.id' => tags(:general).id),
Author.where("tags.id" => tags(:general).id),
[authors(:david)], :tags
)
# This ensures that the polymorphism of taggings is being observed correctly
authors = Author.joins(:tags).where('taggings.taggable_type' => 'FakeModel')
authors = Author.joins(:tags).where("taggings.taggable_type" => "FakeModel")
assert authors.empty?
end
@ -79,7 +79,7 @@ def test_has_many_through_has_many_with_has_many_through_source_reflection_prelo
# Through: has_many through
def test_has_many_through_has_many_through_with_has_many_source_reflection
luke, david = subscribers(:first), subscribers(:second)
assert_equal [luke, david, david], authors(:david).subscribers.order('subscribers.nick')
assert_equal [luke, david, david], authors(:david).subscribers.order("subscribers.nick")
end
def test_has_many_through_has_many_through_with_has_many_source_reflection_preload
@ -93,7 +93,7 @@ def test_has_many_through_has_many_through_with_has_many_source_reflection_prelo
def test_has_many_through_has_many_through_with_has_many_source_reflection_preload_via_joins
# All authors with subscribers where one of the subscribers' nick is 'alterself'
assert_includes_and_joins_equal(
Author.where('subscribers.nick' => 'alterself'),
Author.where("subscribers.nick" => "alterself"),
[authors(:david)], :subscribers
)
end
@ -115,7 +115,7 @@ def test_has_many_through_has_one_with_has_one_through_source_reflection_preload
def test_has_many_through_has_one_with_has_one_through_source_reflection_preload_via_joins
assert_includes_and_joins_equal(
Member.where('member_types.id' => member_types(:founding).id),
Member.where("member_types.id" => member_types(:founding).id),
[members(:groucho)], :nested_member_types
)
end
@ -137,7 +137,7 @@ def test_has_many_through_has_one_through_with_has_one_source_reflection_preload
def test_has_many_through_has_one_through_with_has_one_source_reflection_preload_via_joins
assert_includes_and_joins_equal(
Member.where('sponsors.id' => sponsors(:moustache_club_sponsor_for_groucho).id),
Member.where("sponsors.id" => sponsors(:moustache_club_sponsor_for_groucho).id),
[members(:groucho)], :nested_sponsors
)
end
@ -149,7 +149,7 @@ def test_has_many_through_has_one_with_has_many_through_source_reflection
groucho_details, other_details = member_details(:groucho), member_details(:some_other_guy)
assert_equal [groucho_details, other_details],
members(:groucho).organization_member_details.order('member_details.id')
members(:groucho).organization_member_details.order("member_details.id")
end
def test_has_many_through_has_one_with_has_many_through_source_reflection_preload
@ -164,12 +164,12 @@ def test_has_many_through_has_one_with_has_many_through_source_reflection_preloa
def test_has_many_through_has_one_with_has_many_through_source_reflection_preload_via_joins
assert_includes_and_joins_equal(
Member.where('member_details.id' => member_details(:groucho).id).order('member_details.id'),
Member.where("member_details.id" => member_details(:groucho).id).order("member_details.id"),
[members(:groucho), members(:some_other_guy)], :organization_member_details
)
members = Member.joins(:organization_member_details).
where('member_details.id' => 9)
where("member_details.id" => 9)
assert members.empty?
end
@ -180,7 +180,7 @@ def test_has_many_through_has_one_through_with_has_many_source_reflection
groucho_details, other_details = member_details(:groucho), member_details(:some_other_guy)
assert_equal [groucho_details, other_details],
members(:groucho).organization_member_details_2.order('member_details.id')
members(:groucho).organization_member_details_2.order("member_details.id")
end
def test_has_many_through_has_one_through_with_has_many_source_reflection_preload
@ -196,12 +196,12 @@ def test_has_many_through_has_one_through_with_has_many_source_reflection_preloa
def test_has_many_through_has_one_through_with_has_many_source_reflection_preload_via_joins
assert_includes_and_joins_equal(
Member.where('member_details.id' => member_details(:groucho).id).order('member_details.id'),
Member.where("member_details.id" => member_details(:groucho).id).order("member_details.id"),
[members(:groucho), members(:some_other_guy)], :organization_member_details_2
)
members = Member.joins(:organization_member_details_2).
where('member_details.id' => 9)
where("member_details.id" => 9)
assert members.empty?
end
@ -211,7 +211,7 @@ def test_has_many_through_has_one_through_with_has_many_source_reflection_preloa
def test_has_many_through_has_many_with_has_and_belongs_to_many_source_reflection
general, cooking = categories(:general), categories(:cooking)
assert_equal [general, cooking], authors(:bob).post_categories.order('categories.id')
assert_equal [general, cooking], authors(:bob).post_categories.order("categories.id")
end
def test_has_many_through_has_many_with_has_and_belongs_to_many_source_reflection_preload
@ -228,7 +228,7 @@ def test_has_many_through_has_many_with_has_and_belongs_to_many_source_reflectio
Author.joins(:post_categories).first
assert_includes_and_joins_equal(
Author.where('categories.id' => categories(:cooking).id),
Author.where("categories.id" => categories(:cooking).id),
[authors(:bob)], :post_categories
)
end
@ -239,7 +239,7 @@ def test_has_many_through_has_many_with_has_and_belongs_to_many_source_reflectio
def test_has_many_through_has_and_belongs_to_many_with_has_many_source_reflection
greetings, more = comments(:greetings), comments(:more_greetings)
assert_equal [greetings, more], categories(:technology).post_comments.order('comments.id')
assert_equal [greetings, more], categories(:technology).post_comments.order("comments.id")
end
def test_has_many_through_has_and_belongs_to_many_with_has_many_source_reflection_preload
@ -257,7 +257,7 @@ def test_has_many_through_has_and_belongs_to_many_with_has_many_source_reflectio
Category.joins(:post_comments).first
assert_includes_and_joins_equal(
Category.where('comments.id' => comments(:more_greetings).id).order('categories.id'),
Category.where("comments.id" => comments(:more_greetings).id).order("categories.id"),
[categories(:general), categories(:technology)], :post_comments
)
end
@ -268,7 +268,7 @@ def test_has_many_through_has_and_belongs_to_many_with_has_many_source_reflectio
def test_has_many_through_has_many_with_has_many_through_habtm_source_reflection
greetings, more = comments(:greetings), comments(:more_greetings)
assert_equal [greetings, more], authors(:bob).category_post_comments.order('comments.id')
assert_equal [greetings, more], authors(:bob).category_post_comments.order("comments.id")
end
def test_has_many_through_has_many_with_has_many_through_habtm_source_reflection_preload
@ -285,7 +285,7 @@ def test_has_many_through_has_many_with_has_many_through_habtm_source_reflection
Author.joins(:category_post_comments).first
assert_includes_and_joins_equal(
Author.where('comments.id' => comments(:does_it_hurt).id).order('authors.id'),
Author.where("comments.id" => comments(:does_it_hurt).id).order("authors.id"),
[authors(:david), authors(:mary)], :category_post_comments
)
end
@ -308,7 +308,7 @@ def test_has_many_through_has_many_through_with_belongs_to_source_reflection_pre
def test_has_many_through_has_many_through_with_belongs_to_source_reflection_preload_via_joins
assert_includes_and_joins_equal(
Author.where('tags.id' => tags(:general).id),
Author.where("tags.id" => tags(:general).id),
[authors(:david)], :tagging_tags
)
end
@ -320,7 +320,7 @@ def test_has_many_through_belongs_to_with_has_many_through_source_reflection
welcome_general, thinking_general = taggings(:welcome_general), taggings(:thinking_general)
assert_equal [welcome_general, thinking_general],
categorizations(:david_welcome_general).post_taggings.order('taggings.id')
categorizations(:david_welcome_general).post_taggings.order("taggings.id")
end
def test_has_many_through_belongs_to_with_has_many_through_source_reflection_preload
@ -334,7 +334,7 @@ def test_has_many_through_belongs_to_with_has_many_through_source_reflection_pre
def test_has_many_through_belongs_to_with_has_many_through_source_reflection_preload_via_joins
assert_includes_and_joins_equal(
Categorization.where('taggings.id' => taggings(:welcome_general).id).order('taggings.id'),
Categorization.where("taggings.id" => taggings(:welcome_general).id).order("taggings.id"),
[categorizations(:david_welcome_general)], :post_taggings
)
end
@ -357,7 +357,7 @@ def test_has_one_through_has_one_with_has_one_through_source_reflection_preload
def test_has_one_through_has_one_with_has_one_through_source_reflection_preload_via_joins
assert_includes_and_joins_equal(
Member.where('member_types.id' => member_types(:founding).id),
Member.where("member_types.id" => member_types(:founding).id),
[members(:groucho)], :nested_member_type
)
end
@ -391,7 +391,7 @@ def test_has_one_through_has_one_through_with_belongs_to_source_reflection_prelo
def test_has_one_through_has_one_through_with_belongs_to_source_reflection_preload_via_joins
assert_includes_and_joins_equal(
Member.where('categories.id' => categories(:technology).id),
Member.where("categories.id" => categories(:technology).id),
[members(:blarpy_winkup)], :club_category
)
end
@ -404,7 +404,7 @@ def test_distinct_has_many_through_a_has_many_through_association_on_source_refl
def test_distinct_has_many_through_a_has_many_through_association_on_through_reflection
author = authors(:david)
assert_equal [subscribers(:first), subscribers(:second)],
author.distinct_subscribers.order('subscribers.nick')
author.distinct_subscribers.order("subscribers.nick")
end
def test_nested_has_many_through_with_a_table_referenced_multiple_times
@ -413,26 +413,26 @@ def test_nested_has_many_through_with_a_table_referenced_multiple_times
author.similar_posts.sort_by(&:id)
# Mary and Bob both have posts in misc, but they are the only ones.
authors = Author.joins(:similar_posts).where('posts.id' => posts(:misc_by_bob).id)
authors = Author.joins(:similar_posts).where("posts.id" => posts(:misc_by_bob).id)
assert_equal [authors(:mary), authors(:bob)], authors.distinct.sort_by(&:id)
# Check the polymorphism of taggings is being observed correctly (in both joins)
authors = Author.joins(:similar_posts).where('taggings.taggable_type' => 'FakeModel')
authors = Author.joins(:similar_posts).where("taggings.taggable_type" => "FakeModel")
assert authors.empty?
authors = Author.joins(:similar_posts).where('taggings_authors_join.taggable_type' => 'FakeModel')
authors = Author.joins(:similar_posts).where("taggings_authors_join.taggable_type" => "FakeModel")
assert authors.empty?
end
def test_has_many_through_with_foreign_key_option_on_through_reflection
assert_equal [posts(:welcome), posts(:authorless)], people(:david).agents_posts.order('posts.id')
assert_equal [posts(:welcome), posts(:authorless)], people(:david).agents_posts.order("posts.id")
assert_equal [authors(:david)], references(:david_unicyclist).agents_posts_authors
references = Reference.joins(:agents_posts_authors).where('authors.id' => authors(:david).id)
references = Reference.joins(:agents_posts_authors).where("authors.id" => authors(:david).id)
assert_equal [references(:david_unicyclist)], references
end
def test_has_many_through_with_foreign_key_option_on_source_reflection
assert_equal [people(:michael), people(:susan)], jobs(:unicyclist).agents.order('people.id')
assert_equal [people(:michael), people(:susan)], jobs(:unicyclist).agents.order("people.id")
jobs = Job.joins(:agents)
assert_equal [jobs(:unicyclist), jobs(:unicyclist)], jobs
@ -505,7 +505,7 @@ def test_nested_has_many_through_with_conditions_on_through_associations
end
def test_nested_has_many_through_with_conditions_on_through_associations_preload
assert Author.where('tags.id' => 100).joins(:misc_post_first_blue_tags).empty?
assert Author.where("tags.id" => 100).joins(:misc_post_first_blue_tags).empty?
authors = assert_queries(3) { Author.includes(:misc_post_first_blue_tags).to_a.sort_by(&:id) }
blue = tags(:blue)
@ -518,7 +518,7 @@ def test_nested_has_many_through_with_conditions_on_through_associations_preload
def test_nested_has_many_through_with_conditions_on_through_associations_preload_via_joins
# Pointless condition to force single-query loading
assert_includes_and_joins_equal(
Author.where('tags.id = tags.id').references(:tags),
Author.where("tags.id = tags.id").references(:tags),
[authors(:bob)], :misc_post_first_blue_tags
)
end
@ -539,7 +539,7 @@ def test_nested_has_many_through_with_conditions_on_source_associations_preload
def test_nested_has_many_through_with_conditions_on_source_associations_preload_via_joins
# Pointless condition to force single-query loading
assert_includes_and_joins_equal(
Author.where('tags.id = tags.id').references(:tags),
Author.where("tags.id = tags.id").references(:tags),
[authors(:bob)], :misc_post_first_blue_tags_2
)
end
@ -548,13 +548,13 @@ def test_nested_has_many_through_with_foreign_key_option_on_the_source_reflectio
assert_equal [categories(:general)], organizations(:nsa).author_essay_categories
organizations = Organization.joins(:author_essay_categories).
where('categories.id' => categories(:general).id)
where("categories.id" => categories(:general).id)
assert_equal [organizations(:nsa)], organizations
assert_equal categories(:general), organizations(:nsa).author_owned_essay_category
organizations = Organization.joins(:author_owned_essay_category).
where('categories.id' => categories(:general).id)
where("categories.id" => categories(:general).id)
assert_equal [organizations(:nsa)], organizations
end

@ -18,8 +18,8 @@ class Child < ActiveRecord::Base
end
teardown do
@connection.drop_table 'parents', if_exists: true
@connection.drop_table 'children', if_exists: true
@connection.drop_table "parents", if_exists: true
@connection.drop_table "children", if_exists: true
end
test "belongs_to associations are not required by default" do

@ -1,36 +1,36 @@
require "cases/helper"
require 'models/computer'
require 'models/developer'
require 'models/project'
require 'models/company'
require 'models/categorization'
require 'models/category'
require 'models/post'
require 'models/author'
require 'models/comment'
require 'models/tag'
require 'models/tagging'
require 'models/person'
require 'models/reader'
require 'models/ship_part'
require 'models/ship'
require 'models/liquid'
require 'models/molecule'
require 'models/electron'
require 'models/man'
require 'models/interest'
require "models/computer"
require "models/developer"
require "models/project"
require "models/company"
require "models/categorization"
require "models/category"
require "models/post"
require "models/author"
require "models/comment"
require "models/tag"
require "models/tagging"
require "models/person"
require "models/reader"
require "models/ship_part"
require "models/ship"
require "models/liquid"
require "models/molecule"
require "models/electron"
require "models/man"
require "models/interest"
class AssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :companies, :developers, :projects, :developers_projects,
: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
@ -52,24 +52,24 @@ def test_loading_the_association_target_should_load_most_recent_attributes_for_c
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
ShipPart.find(part.id).update_columns(name: "Deck")
assert_equal "Deck", ship.parts[0].name
end
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}
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')
assert_raise(ArgumentError, "ActiveRecord should have barked on bad collection keys") do
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")
@ -120,7 +120,7 @@ def test_force_reload_is_uncached
def test_association_with_references
firm = companies(:first_firm)
assert_includes firm.association_with_references.references_values, 'foo'
assert_includes firm.association_with_references.references_values, "foo"
end
end
@ -190,7 +190,7 @@ 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
@ -225,7 +225,7 @@ def test_proxy_association_accessor
end
def test_scoped_allows_conditions
assert developers(:david).projects.merge(where: 'foo').to_sql.include?('foo')
assert developers(:david).projects.merge(where: "foo").to_sql.include?("foo")
end
test "getting a scope from an association" do
@ -280,10 +280,10 @@ class PeopleList < ActiveRecord::Base
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

@ -1,9 +1,9 @@
require 'cases/helper'
require "cases/helper"
module ActiveRecord
class AttributeDecoratorsTest < ActiveRecord::TestCase
class Model < ActiveRecord::Base
self.table_name = 'attribute_decorators_model'
self.table_name = "attribute_decorators_model"
end
class StringDecorator < SimpleDelegator
@ -28,19 +28,19 @@ def cast(value)
teardown do
return unless @connection
@connection.drop_table 'attribute_decorators_model', if_exists: true
@connection.drop_table "attribute_decorators_model", if_exists: true
Model.attribute_type_decorations.clear
Model.reset_column_information
end
test "attributes can be decorated" do
model = Model.new(a_string: 'Hello')
assert_equal 'Hello', model.a_string
model = Model.new(a_string: "Hello")
assert_equal "Hello", model.a_string
Model.decorate_attribute_type(:a_string, :test) { |t| StringDecorator.new(t) }
model = Model.new(a_string: 'Hello')
assert_equal 'Hello decorated!', model.a_string
model = Model.new(a_string: "Hello")
assert_equal "Hello decorated!", model.a_string
end
test "decoration does not eagerly load existing columns" do
@ -51,54 +51,54 @@ def cast(value)
end
test "undecorated columns are not touched" do
Model.attribute :another_string, :string, default: 'something or other'
Model.attribute :another_string, :string, default: "something or other"
Model.decorate_attribute_type(:a_string, :test) { |t| StringDecorator.new(t) }
assert_equal 'something or other', Model.new.another_string
assert_equal "something or other", Model.new.another_string
end
test "decorators can be chained" do
Model.decorate_attribute_type(:a_string, :test) { |t| StringDecorator.new(t) }
Model.decorate_attribute_type(:a_string, :other) { |t| StringDecorator.new(t) }
model = Model.new(a_string: 'Hello!')
model = Model.new(a_string: "Hello!")
assert_equal 'Hello! decorated! decorated!', model.a_string
assert_equal "Hello! decorated! decorated!", model.a_string
end
test "decoration of the same type multiple times is idempotent" do
Model.decorate_attribute_type(:a_string, :test) { |t| StringDecorator.new(t) }
Model.decorate_attribute_type(:a_string, :test) { |t| StringDecorator.new(t) }
model = Model.new(a_string: 'Hello')
assert_equal 'Hello decorated!', model.a_string
model = Model.new(a_string: "Hello")
assert_equal "Hello decorated!", model.a_string
end
test "decorations occur in order of declaration" do
Model.decorate_attribute_type(:a_string, :test) { |t| StringDecorator.new(t) }
Model.decorate_attribute_type(:a_string, :other) do |type|
StringDecorator.new(type, 'decorated again!')
StringDecorator.new(type, "decorated again!")
end
model = Model.new(a_string: 'Hello!')
model = Model.new(a_string: "Hello!")
assert_equal 'Hello! decorated! decorated again!', model.a_string
assert_equal "Hello! decorated! decorated again!", model.a_string
end
test "decorating attributes does not modify parent classes" do
Model.attribute :another_string, :string, default: 'whatever'
Model.attribute :another_string, :string, default: "whatever"
Model.decorate_attribute_type(:a_string, :test) { |t| StringDecorator.new(t) }
child_class = Class.new(Model)
child_class.decorate_attribute_type(:another_string, :test) { |t| StringDecorator.new(t) }
child_class.decorate_attribute_type(:a_string, :other) { |t| StringDecorator.new(t) }
model = Model.new(a_string: 'Hello!')
child = child_class.new(a_string: 'Hello!')
model = Model.new(a_string: "Hello!")
child = child_class.new(a_string: "Hello!")
assert_equal 'Hello! decorated!', model.a_string
assert_equal 'whatever', model.another_string
assert_equal 'Hello! decorated! decorated!', child.a_string
assert_equal 'whatever decorated!', child.another_string
assert_equal "Hello! decorated!", model.a_string
assert_equal "whatever", model.another_string
assert_equal "Hello! decorated! decorated!", child.a_string
assert_equal "whatever decorated!", child.another_string
end
class Multiplier < SimpleDelegator
@ -116,9 +116,9 @@ def cast(value)
Multiplier.new(type)
end
model = Model.new(a_string: 'whatever', an_int: 1)
model = Model.new(a_string: "whatever", an_int: 1)
assert_equal 'whatever', model.a_string
assert_equal "whatever", model.a_string
assert_equal 2, model.an_int
end
end

@ -1,5 +1,5 @@
require "cases/helper"
require 'thread'
require "thread"
module ActiveRecord
module AttributeMethods

@ -1,15 +1,15 @@
require "cases/helper"
require 'models/minimalistic'
require 'models/developer'
require 'models/auto_id'
require 'models/boolean'
require 'models/computer'
require 'models/topic'
require 'models/company'
require 'models/category'
require 'models/reply'
require 'models/contact'
require 'models/keyboard'
require "models/minimalistic"
require "models/developer"
require "models/auto_id"
require "models/boolean"
require "models/computer"
require "models/topic"
require "models/company"
require "models/category"
require "models/reply"
require "models/contact"
require "models/keyboard"
class AttributeMethodsTest < ActiveRecord::TestCase
include InTimeZone
@ -19,7 +19,7 @@ class AttributeMethodsTest < ActiveRecord::TestCase
def setup
@old_matchers = ActiveRecord::Base.send(:attribute_method_matchers).dup
@target = Class.new(ActiveRecord::Base)
@target.table_name = 'topics'
@target.table_name = "topics"
end
teardown do
@ -27,34 +27,34 @@ def setup
ActiveRecord::Base.send(:attribute_method_matchers).concat(@old_matchers)
end
test 'attribute_for_inspect with a string' do
test "attribute_for_inspect with a string" do
t = topics(:first)
t.title = "The First Topic Now Has A Title With\nNewlines And More Than 50 Characters"
assert_equal '"The First Topic Now Has A Title With\nNewlines And ..."', t.attribute_for_inspect(:title)
end
test 'attribute_for_inspect with a date' do
test "attribute_for_inspect with a date" do
t = topics(:first)
assert_equal %("#{t.written_on.to_s(:db)}"), t.attribute_for_inspect(:written_on)
end
test 'attribute_for_inspect with an array' do
test "attribute_for_inspect with an array" do
t = topics(:first)
t.content = [Object.new]
assert_match %r(\[#<Object:0x[0-9a-f]+>\]), t.attribute_for_inspect(:content)
end
test 'attribute_for_inspect with a long array' do
test "attribute_for_inspect with a long array" do
t = topics(:first)
t.content = (1..11).to_a
assert_equal "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]", t.attribute_for_inspect(:content)
end
test 'attribute_present' do
test "attribute_present" do
t = Topic.new
t.title = "hello there!"
t.written_on = Time.now
@ -65,7 +65,7 @@ def setup
assert !t.attribute_present?("author_name")
end
test 'attribute_present with booleans' do
test "attribute_present with booleans" do
b1 = Boolean.new
b1.value = false
assert b1.attribute_present?(:value)
@ -83,44 +83,44 @@ def setup
assert Boolean.find(b4.id).attribute_present?(:value)
end
test 'caching a nil primary key' do
test "caching a nil primary key" do
klass = Class.new(Minimalistic)
assert_called(klass, :reset_primary_key, returns: nil) do
2.times { klass.primary_key }
end
end
test 'attribute keys on a new instance' do
test "attribute keys on a new instance" do
t = Topic.new
assert_equal nil, t.title, "The topics table has a title column, so it should be nil"
assert_raise(NoMethodError) { t.title2 }
end
test 'boolean attributes' do
test "boolean attributes" do
assert !Topic.find(1).approved?
assert Topic.find(2).approved?
end
test 'set attributes' do
test "set attributes" do
topic = Topic.find(1)
topic.attributes = { title: 'Budget', author_name: 'Jason' }
topic.attributes = { title: "Budget", author_name: "Jason" }
topic.save
assert_equal('Budget', topic.title)
assert_equal('Jason', topic.author_name)
assert_equal("Budget", topic.title)
assert_equal("Jason", topic.author_name)
assert_equal(topics(:first).author_email_address, Topic.find(1).author_email_address)
end
test 'set attributes without a hash' do
test "set attributes without a hash" do
topic = Topic.new
assert_raise(ArgumentError) { topic.attributes = '' }
assert_raise(ArgumentError) { topic.attributes = "" }
end
test 'integers as nil' do
test = AutoId.create(value: '')
test "integers as nil" do
test = AutoId.create(value: "")
assert_nil AutoId.find(test.id).value
end
test 'set attributes with a block' do
test "set attributes with a block" do
topic = Topic.new do |t|
t.title = "Budget"
t.author_name = "Jason"
@ -130,7 +130,7 @@ def setup
assert_equal("Jason", topic.author_name)
end
test 'respond_to?' do
test "respond_to?" do
topic = Topic.find(1)
assert_respond_to topic, "title"
assert_respond_to topic, "title?"
@ -144,27 +144,27 @@ def setup
assert !topic.respond_to?(:nothingness)
end
test 'respond_to? with a custom primary key' do
test "respond_to? with a custom primary key" do
keyboard = Keyboard.create
assert_not_nil keyboard.key_number
assert_equal keyboard.key_number, keyboard.id
assert keyboard.respond_to?('key_number')
assert keyboard.respond_to?('id')
assert keyboard.respond_to?("key_number")
assert keyboard.respond_to?("id")
end
test 'id_before_type_cast with a custom primary key' do
test "id_before_type_cast with a custom primary key" do
keyboard = Keyboard.create
keyboard.key_number = '10'
assert_equal '10', keyboard.id_before_type_cast
assert_equal nil, keyboard.read_attribute_before_type_cast('id')
assert_equal '10', keyboard.read_attribute_before_type_cast('key_number')
assert_equal '10', keyboard.read_attribute_before_type_cast(:key_number)
keyboard.key_number = "10"
assert_equal "10", keyboard.id_before_type_cast
assert_equal nil, keyboard.read_attribute_before_type_cast("id")
assert_equal "10", keyboard.read_attribute_before_type_cast("key_number")
assert_equal "10", keyboard.read_attribute_before_type_cast(:key_number)
end
# Syck calls respond_to? before actually calling initialize.
test 'respond_to? with an allocated object' do
test "respond_to? with an allocated object" do
klass = Class.new(ActiveRecord::Base) do
self.table_name = 'topics'
self.table_name = "topics"
end
topic = klass.allocate
@ -175,12 +175,12 @@ def setup
end
# IRB inspects the return value of MyModel.allocate.
test 'allocated objects can be inspected' do
test "allocated objects can be inspected" do
topic = Topic.allocate
assert_equal "#<Topic not initialized>", topic.inspect
end
test 'array content' do
test "array content" do
content = %w( one two three )
topic = Topic.new
topic.content = content
@ -189,16 +189,16 @@ def setup
assert_equal content, Topic.find(topic.id).content
end
test 'read attributes_before_type_cast' do
category = Category.new(name: 'Test category', type: nil)
category_attrs = { 'name' => 'Test category', 'id' => nil, 'type' => nil, 'categorizations_count' => nil }
test "read attributes_before_type_cast" do
category = Category.new(name: "Test category", type: nil)
category_attrs = { "name" => "Test category", "id" => nil, "type" => nil, "categorizations_count" => nil }
assert_equal category_attrs, category.attributes_before_type_cast
end
if current_adapter?(:Mysql2Adapter)
test 'read attributes_before_type_cast on a boolean' do
test "read attributes_before_type_cast on a boolean" do
bool = Boolean.create!({ "value" => false })
if RUBY_PLATFORM.include?('java')
if RUBY_PLATFORM.include?("java")
# JRuby will return the value before typecast as string.
assert_equal "0", bool.reload.attributes_before_type_cast["value"]
else
@ -207,7 +207,7 @@ def setup
end
end
test 'read attributes_before_type_cast on a datetime' do
test "read attributes_before_type_cast on a datetime" do
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new
@ -222,7 +222,7 @@ def setup
end
end
test 'read attributes_after_type_cast on a date' do
test "read attributes_after_type_cast on a date" do
tz = "Pacific Time (US & Canada)"
in_time_zone tz do
@ -243,7 +243,7 @@ def setup
end
end
test 'hash content' do
test "hash content" do
topic = Topic.new
topic.content = { "one" => 1, "two" => 2 }
topic.save
@ -257,7 +257,7 @@ def setup
assert_equal 3, Topic.find(topic.id).content["three"]
end
test 'update array content' do
test "update array content" do
topic = Topic.new
topic.content = %w( one two three )
@ -271,25 +271,25 @@ def setup
assert_equal(%w( one two three four five ), topic.content)
end
test 'case-sensitive attributes hash' do
test "case-sensitive attributes hash" do
# DB2 is not case-sensitive.
return true if current_adapter?(:DB2Adapter)
assert_equal @loaded_fixtures['computers']['workstation'].to_hash, Computer.first.attributes
assert_equal @loaded_fixtures["computers"]["workstation"].to_hash, Computer.first.attributes
end
test 'attributes without primary key' do
test "attributes without primary key" do
klass = Class.new(ActiveRecord::Base) do
self.table_name = 'developers_projects'
self.table_name = "developers_projects"
end
assert_equal klass.column_names, klass.new.attributes.keys
assert_not klass.new.has_attribute?('id')
assert_not klass.new.has_attribute?("id")
end
test 'hashes are not mangled' do
new_topic = { title: 'New Topic' }
new_topic_values = { title: 'AnotherTopic' }
test "hashes are not mangled" do
new_topic = { title: "New Topic" }
new_topic_values = { title: "AnotherTopic" }
topic = Topic.new(new_topic)
assert_equal new_topic[:title], topic.title
@ -298,13 +298,13 @@ def setup
assert_equal new_topic_values[:title], topic.title
end
test 'create through factory' do
topic = Topic.create(title: 'New Topic')
test "create through factory" do
topic = Topic.create(title: "New Topic")
topicReloaded = Topic.find(topic.id)
assert_equal(topic, topicReloaded)
end
test 'write_attribute' do
test "write_attribute" do
topic = Topic.new
topic.send(:write_attribute, :title, "Still another topic")
assert_equal "Still another topic", topic.title
@ -319,7 +319,7 @@ def setup
assert_equal "Still another topic: part 4", topic.title
end
test 'read_attribute' do
test "read_attribute" do
topic = Topic.new
topic.title = "Don't change the topic"
assert_equal "Don't change the topic", topic.read_attribute("title")
@ -329,15 +329,15 @@ def setup
assert_equal "Don't change the topic", topic[:title]
end
test 'read_attribute raises ActiveModel::MissingAttributeError when the attribute does not exist' do
computer = Computer.select('id').first
test "read_attribute raises ActiveModel::MissingAttributeError when the attribute does not exist" do
computer = Computer.select("id").first
assert_raises(ActiveModel::MissingAttributeError) { computer[:developer] }
assert_raises(ActiveModel::MissingAttributeError) { computer[:extendedWarranty] }
assert_raises(ActiveModel::MissingAttributeError) { computer[:no_column_exists] = 'Hello!' }
assert_nothing_raised { computer[:developer] = 'Hello!' }
assert_raises(ActiveModel::MissingAttributeError) { computer[:no_column_exists] = "Hello!" }
assert_nothing_raised { computer[:developer] = "Hello!" }
end
test 'read_attribute when false' do
test "read_attribute when false" do
topic = topics(:first)
topic.approved = false
assert !topic.approved?, "approved should be false"
@ -345,7 +345,7 @@ def setup
assert !topic.approved?, "approved should be false"
end
test 'read_attribute when true' do
test "read_attribute when true" do
topic = topics(:first)
topic.approved = true
assert topic.approved?, "approved should be true"
@ -353,7 +353,7 @@ def setup
assert topic.approved?, "approved should be true"
end
test 'boolean attributes writing and reading' do
test "boolean attributes writing and reading" do
topic = Topic.new
topic.approved = "false"
assert !topic.approved?, "approved should be false"
@ -368,7 +368,7 @@ def setup
assert topic.approved?, "approved should be true"
end
test 'overridden write_attribute' do
test "overridden write_attribute" do
topic = Topic.new
def topic.write_attribute(attr_name, value)
super(attr_name, value.downcase)
@ -387,7 +387,7 @@ def topic.write_attribute(attr_name, value)
assert_equal "yet another topic: part 4", topic.title
end
test 'overridden read_attribute' do
test "overridden read_attribute" do
topic = Topic.new
topic.title = "Stop changing the topic"
def topic.read_attribute(attr_name)
@ -401,30 +401,30 @@ def topic.read_attribute(attr_name)
assert_equal "STOP CHANGING THE TOPIC", topic[:title]
end
test 'read overridden attribute' do
topic = Topic.new(title: 'a')
def topic.title() 'b' end
assert_equal 'a', topic[:title]
test "read overridden attribute" do
topic = Topic.new(title: "a")
def topic.title() "b" end
assert_equal "a", topic[:title]
end
test 'string attribute predicate' do
test "string attribute predicate" do
[nil, "", " "].each do |value|
assert_equal false, Topic.new(author_name: value).author_name?
end
assert_equal true, Topic.new(author_name: 'Name').author_name?
assert_equal true, Topic.new(author_name: "Name").author_name?
end
test 'number attribute predicate' do
[nil, 0, '0'].each do |value|
test "number attribute predicate" do
[nil, 0, "0"].each do |value|
assert_equal false, Developer.new(salary: value).salary?
end
assert_equal true, Developer.new(salary: 1).salary?
assert_equal true, Developer.new(salary: '1').salary?
assert_equal true, Developer.new(salary: "1").salary?
end
test 'boolean attribute predicate' do
test "boolean attribute predicate" do
[nil, "", false, "false", "f", 0].each do |value|
assert_equal false, Topic.new(approved: value).approved?
end
@ -434,7 +434,7 @@ def topic.title() 'b' end
end
end
test 'custom field attribute predicate' do
test "custom field attribute predicate" do
object = Company.find_by_sql(<<-SQL).first
SELECT c1.*, c2.type as string_value, c2.rating as int_value
FROM companies c1, companies c2
@ -455,93 +455,93 @@ def topic.title() 'b' end
assert !object.int_value?
end
test 'non-attribute read and write' do
test "non-attribute read and write" do
topic = Topic.new
assert !topic.respond_to?("mumbo")
assert_raise(NoMethodError) { topic.mumbo }
assert_raise(NoMethodError) { topic.mumbo = 5 }
end
test 'undeclared attribute method does not affect respond_to? and method_missing' do
topic = @target.new(title: 'Budget')
assert topic.respond_to?('title')
assert_equal 'Budget', topic.title
assert !topic.respond_to?('title_hello_world')
test "undeclared attribute method does not affect respond_to? and method_missing" do
topic = @target.new(title: "Budget")
assert topic.respond_to?("title")
assert_equal "Budget", topic.title
assert !topic.respond_to?("title_hello_world")
assert_raise(NoMethodError) { topic.title_hello_world }
end
test 'declared prefixed attribute method affects respond_to? and method_missing' do
topic = @target.new(title: 'Budget')
test "declared prefixed attribute method affects respond_to? and method_missing" do
topic = @target.new(title: "Budget")
%w(default_ title_).each do |prefix|
@target.class_eval "def #{prefix}attribute(*args) args end"
@target.attribute_method_prefix prefix
meth = "#{prefix}title"
assert topic.respond_to?(meth)
assert_equal ['title'], topic.send(meth)
assert_equal ['title', 'a'], topic.send(meth, 'a')
assert_equal ['title', 1, 2, 3], topic.send(meth, 1, 2, 3)
assert_equal ["title"], topic.send(meth)
assert_equal ["title", "a"], topic.send(meth, "a")
assert_equal ["title", 1, 2, 3], topic.send(meth, 1, 2, 3)
end
end
test 'declared suffixed attribute method affects respond_to? and method_missing' do
test "declared suffixed attribute method affects respond_to? and method_missing" do
%w(_default _title_default _it! _candidate= able?).each do |suffix|
@target.class_eval "def attribute#{suffix}(*args) args end"
@target.attribute_method_suffix suffix
topic = @target.new(title: 'Budget')
topic = @target.new(title: "Budget")
meth = "title#{suffix}"
assert topic.respond_to?(meth)
assert_equal ['title'], topic.send(meth)
assert_equal ['title', 'a'], topic.send(meth, 'a')
assert_equal ['title', 1, 2, 3], topic.send(meth, 1, 2, 3)
assert_equal ["title"], topic.send(meth)
assert_equal ["title", "a"], topic.send(meth, "a")
assert_equal ["title", 1, 2, 3], topic.send(meth, 1, 2, 3)
end
end
test 'declared affixed attribute method affects respond_to? and method_missing' do
[['mark_', '_for_update'], ['reset_', '!'], ['default_', '_value?']].each do |prefix, suffix|
test "declared affixed attribute method affects respond_to? and method_missing" do
[["mark_", "_for_update"], ["reset_", "!"], ["default_", "_value?"]].each do |prefix, suffix|
@target.class_eval "def #{prefix}attribute#{suffix}(*args) args end"
@target.attribute_method_affix(prefix: prefix, suffix: suffix)
topic = @target.new(title: 'Budget')
topic = @target.new(title: "Budget")
meth = "#{prefix}title#{suffix}"
assert topic.respond_to?(meth)
assert_equal ['title'], topic.send(meth)
assert_equal ['title', 'a'], topic.send(meth, 'a')
assert_equal ['title', 1, 2, 3], topic.send(meth, 1, 2, 3)
assert_equal ["title"], topic.send(meth)
assert_equal ["title", "a"], topic.send(meth, "a")
assert_equal ["title", 1, 2, 3], topic.send(meth, 1, 2, 3)
end
end
test 'should unserialize attributes for frozen records' do
test "should unserialize attributes for frozen records" do
myobj = { value1: :value2 }
topic = Topic.create(content: myobj)
topic.freeze
assert_equal myobj, topic.content
end
test 'typecast attribute from select to false' do
Topic.create(title: 'Budget')
test "typecast attribute from select to false" do
Topic.create(title: "Budget")
# Oracle does not support boolean expressions in SELECT.
if current_adapter?(:OracleAdapter, :FbAdapter)
topic = Topic.all.merge!(select: 'topics.*, 0 as is_test').first
topic = Topic.all.merge!(select: "topics.*, 0 as is_test").first
else
topic = Topic.all.merge!(select: 'topics.*, 1=2 as is_test').first
topic = Topic.all.merge!(select: "topics.*, 1=2 as is_test").first
end
assert !topic.is_test?
end
test 'typecast attribute from select to true' do
Topic.create(title: 'Budget')
test "typecast attribute from select to true" do
Topic.create(title: "Budget")
# Oracle does not support boolean expressions in SELECT.
if current_adapter?(:OracleAdapter, :FbAdapter)
topic = Topic.all.merge!(select: 'topics.*, 1 as is_test').first
topic = Topic.all.merge!(select: "topics.*, 1 as is_test").first
else
topic = Topic.all.merge!(select: 'topics.*, 2=2 as is_test').first
topic = Topic.all.merge!(select: "topics.*, 2=2 as is_test").first
end
assert topic.is_test?
end
test 'raises ActiveRecord::DangerousAttributeError when defining an AR method in a model' do
test "raises ActiveRecord::DangerousAttributeError when defining an AR method in a model" do
%w(save create_or_update).each do |method|
klass = Class.new(ActiveRecord::Base)
klass.class_eval "def #{method}() 'defined #{method}' end"
@ -551,7 +551,7 @@ def topic.title() 'b' end
end
end
test 'converted values are returned after assignment' do
test "converted values are returned after assignment" do
developer = Developer.new(name: 1337, salary: "50000")
assert_equal "50000", developer.salary_before_type_cast
@ -566,7 +566,7 @@ def topic.title() 'b' end
assert_equal "1337", developer.name
end
test 'write nil to time attribute' do
test "write nil to time attribute" do
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new
record.written_on = nil
@ -574,7 +574,7 @@ def topic.title() 'b' end
end
end
test 'write time to date attribute' do
test "write time to date attribute" do
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new
record.last_read = Time.utc(2010, 1, 1, 10)
@ -582,7 +582,7 @@ def topic.title() 'b' end
end
end
test 'time attributes are retrieved in the current time zone' do
test "time attributes are retrieved in the current time zone" do
in_time_zone "Pacific Time (US & Canada)" do
utc_time = Time.utc(2008, 1, 1)
record = @target.new
@ -594,7 +594,7 @@ def topic.title() 'b' end
end
end
test 'setting a time zone-aware attribute to UTC' do
test "setting a time zone-aware attribute to UTC" do
in_time_zone "Pacific Time (US & Canada)" do
utc_time = Time.utc(2008, 1, 1)
record = @target.new
@ -605,7 +605,7 @@ def topic.title() 'b' end
end
end
test 'setting time zone-aware attribute in other time zone' do
test "setting time zone-aware attribute in other time zone" do
utc_time = Time.utc(2008, 1, 1)
cst_time = utc_time.in_time_zone("Central Time (US & Canada)")
in_time_zone "Pacific Time (US & Canada)" do
@ -617,7 +617,7 @@ def topic.title() 'b' end
end
end
test 'setting time zone-aware read attribute' do
test "setting time zone-aware read attribute" do
utc_time = Time.utc(2008, 1, 1)
cst_time = utc_time.in_time_zone("Central Time (US & Canada)")
in_time_zone "Pacific Time (US & Canada)" do
@ -628,7 +628,7 @@ def topic.title() 'b' end
end
end
test 'setting time zone-aware attribute with a string' do
test "setting time zone-aware attribute with a string" do
utc_time = Time.utc(2008, 1, 1)
(-11..13).each do |timezone_offset|
time_string = utc_time.in_time_zone(timezone_offset).to_s
@ -642,27 +642,27 @@ def topic.title() 'b' end
end
end
test 'time zone-aware attribute saved' do
test "time zone-aware attribute saved" do
in_time_zone 1 do
record = @target.create(written_on: '2012-02-20 10:00')
record = @target.create(written_on: "2012-02-20 10:00")
record.written_on = '2012-02-20 09:00'
record.written_on = "2012-02-20 09:00"
record.save
assert_equal Time.zone.local(2012, 02, 20, 9), record.reload.written_on
end
end
test 'setting a time zone-aware attribute to a blank string returns nil' do
test "setting a time zone-aware attribute to a blank string returns nil" do
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new
record.written_on = ' '
record.written_on = " "
assert_nil record.written_on
assert_nil record[:written_on]
end
end
test 'setting a time zone-aware attribute interprets time zone-unaware string in time zone' do
time_string = 'Tue Jan 01 00:00:00 2008'
test "setting a time zone-aware attribute interprets time zone-unaware string in time zone" do
time_string = "Tue Jan 01 00:00:00 2008"
(-11..13).each do |timezone_offset|
in_time_zone timezone_offset do
record = @target.new
@ -674,7 +674,7 @@ def topic.title() 'b' end
end
end
test 'setting a time zone-aware datetime in the current time zone' do
test "setting a time zone-aware datetime in the current time zone" do
utc_time = Time.utc(2008, 1, 1)
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new
@ -685,7 +685,7 @@ def topic.title() 'b' end
end
end
test 'YAML dumping a record with time zone-aware attribute' do
test "YAML dumping a record with time zone-aware attribute" do
in_time_zone "Pacific Time (US & Canada)" do
record = Topic.new(id: 1)
record.written_on = "Jan 01 00:00:00 2014"
@ -693,7 +693,7 @@ def topic.title() 'b' end
end
end
test 'setting a time zone-aware time in the current time zone' do
test "setting a time zone-aware time in the current time zone" do
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new
time_string = "10:00:00"
@ -703,12 +703,12 @@ def topic.title() 'b' end
assert_equal expected_time, record.bonus_time
assert_equal ActiveSupport::TimeZone["Pacific Time (US & Canada)"], record.bonus_time.time_zone
record.bonus_time = ''
record.bonus_time = ""
assert_nil record.bonus_time
end
end
test 'setting a time zone-aware time with DST' do
test "setting a time zone-aware time with DST" do
in_time_zone "Pacific Time (US & Canada)" do
current_time = Time.zone.local(2014, 06, 15, 10)
record = @target.new(bonus_time: current_time)
@ -722,7 +722,7 @@ def topic.title() 'b' end
end
end
test 'removing time zone-aware types' do
test "removing time zone-aware types" do
with_time_zone_aware_types(:datetime) do
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new(bonus_time: "10:00:00")
@ -734,14 +734,14 @@ def topic.title() 'b' end
end
end
test 'time zone-aware attributes do not recurse infinitely on invalid values' do
test "time zone-aware attributes do not recurse infinitely on invalid values" do
in_time_zone "Pacific Time (US & Canada)" do
record = @target.new(bonus_time: [])
assert_equal nil, record.bonus_time
end
end
test 'setting a time_zone_conversion_for_attributes should write the value on a class variable' do
test "setting a time_zone_conversion_for_attributes should write the value on a class variable" do
Topic.skip_time_zone_conversion_for_attributes = [:field_a]
Minimalistic.skip_time_zone_conversion_for_attributes = [:field_b]
@ -749,44 +749,44 @@ def topic.title() 'b' end
assert_equal [:field_b], Minimalistic.skip_time_zone_conversion_for_attributes
end
test 'attribute readers respect access control' do
privatize('title')
test "attribute readers respect access control" do
privatize("title")
topic = @target.new(title: 'The pros and cons of programming naked.')
topic = @target.new(title: "The pros and cons of programming naked.")
assert !topic.respond_to?(:title)
exception = assert_raise(NoMethodError) { topic.title }
assert exception.message.include?('private method')
assert exception.message.include?("private method")
assert_equal "I'm private", topic.send(:title)
end
test 'attribute writers respect access control' do
privatize('title=(value)')
test "attribute writers respect access control" do
privatize("title=(value)")
topic = @target.new
assert !topic.respond_to?(:title=)
exception = assert_raise(NoMethodError) { topic.title = 'Pants' }
assert exception.message.include?('private method')
topic.send(:title=, 'Very large pants')
exception = assert_raise(NoMethodError) { topic.title = "Pants" }
assert exception.message.include?("private method")
topic.send(:title=, "Very large pants")
end
test 'attribute predicates respect access control' do
privatize('title?')
test "attribute predicates respect access control" do
privatize("title?")
topic = @target.new(title: "Isaac Newton's pants")
assert !topic.respond_to?(:title?)
exception = assert_raise(NoMethodError) { topic.title? }
assert exception.message.include?('private method')
assert exception.message.include?("private method")
assert topic.send(:title?)
end
test 'bulk updates respect access control' do
privatize('title=(value)')
test "bulk updates respect access control" do
privatize("title=(value)")
assert_raise(ActiveRecord::UnknownAttributeError) { @target.new(title: 'Rants about pants') }
assert_raise(ActiveRecord::UnknownAttributeError) { @target.new.attributes = { title: 'Ants in pants' } }
assert_raise(ActiveRecord::UnknownAttributeError) { @target.new(title: "Rants about pants") }
assert_raise(ActiveRecord::UnknownAttributeError) { @target.new.attributes = { title: "Ants in pants" } }
end
test 'bulk update raises ActiveRecord::UnknownAttributeError' do
test "bulk update raises ActiveRecord::UnknownAttributeError" do
error = assert_raises(ActiveRecord::UnknownAttributeError) {
Topic.new(hello: "world")
}
@ -795,7 +795,7 @@ def topic.title() 'b' end
assert_equal "unknown attribute 'hello' for Topic.", error.message
end
test 'method overrides in multi-level subclasses' do
test "method overrides in multi-level subclasses" do
klass = Class.new(Developer) do
def name
"dev:#{read_attribute(:name)}"
@ -803,14 +803,14 @@ def name
end
2.times { klass = Class.new(klass) }
dev = klass.new(name: 'arthurnn')
dev = klass.new(name: "arthurnn")
dev.save!
assert_equal 'dev:arthurnn', dev.reload.name
assert_equal "dev:arthurnn", dev.reload.name
end
test 'global methods are overwritten' do
test "global methods are overwritten" do
klass = Class.new(ActiveRecord::Base) do
self.table_name = 'computers'
self.table_name = "computers"
end
assert !klass.instance_method_already_implemented?(:system)
@ -818,13 +818,13 @@ def name
assert_nil computer.system
end
test 'global methods are overwritten when subclassing' do
test "global methods are overwritten when subclassing" do
klass = Class.new(ActiveRecord::Base) do
self.abstract_class = true
end
subklass = Class.new(klass) do
self.table_name = 'computers'
self.table_name = "computers"
end
assert !klass.instance_method_already_implemented?(:system)
@ -833,7 +833,7 @@ def name
assert_nil computer.system
end
test 'instance methods should be defined on the base class' do
test "instance methods should be defined on the base class" do
subklass = Class.new(Topic)
Topic.define_attribute_methods
@ -849,14 +849,14 @@ def name
assert subklass.method_defined?(:id), "subklass is missing id method"
end
test 'read_attribute with nil should not asplode' do
test "read_attribute with nil should not asplode" do
assert_nil Topic.new.read_attribute(nil)
end
# If B < A, and A defines an accessor for 'foo', we don't want to override
# that by defining a 'foo' method in the generated methods module for B.
# (That module will be inserted between the two, e.g. [B, <GeneratedAttributes>, A].)
test 'inherited custom accessors' do
test "inherited custom accessors" do
klass = new_topic_like_ar_class do
self.abstract_class = true
def title; "omg"; end
@ -872,9 +872,9 @@ def title=(val); self.author_name = val; end
assert_equal "lol", topic.author_name
end
test 'inherited custom accessors with reserved names' do
test "inherited custom accessors with reserved names" do
klass = Class.new(ActiveRecord::Base) do
self.table_name = 'computers'
self.table_name = "computers"
self.abstract_class = true
def system; "omg"; end
def system=(val); self.developer = val; end
@ -890,18 +890,18 @@ def system=(val); self.developer = val; end
assert_equal 99, computer.developer
end
test 'on_the_fly_super_invokable_generated_attribute_methods_via_method_missing' do
test "on_the_fly_super_invokable_generated_attribute_methods_via_method_missing" do
klass = new_topic_like_ar_class do
def title
super + '!'
super + "!"
end
end
real_topic = topics(:first)
assert_equal real_topic.title + '!', klass.find(real_topic.id).title
assert_equal real_topic.title + "!", klass.find(real_topic.id).title
end
test 'on-the-fly super-invokable generated attribute predicates via method_missing' do
test "on-the-fly super-invokable generated attribute predicates via method_missing" do
klass = new_topic_like_ar_class do
def title?
!super
@ -912,7 +912,7 @@ def title?
assert_equal !real_topic.title?, klass.find(real_topic.id).title?
end
test 'calling super when the parent does not define method raises NoMethodError' do
test "calling super when the parent does not define method raises NoMethodError" do
klass = new_topic_like_ar_class do
def some_method_that_is_not_on_super
super
@ -924,38 +924,38 @@ def some_method_that_is_not_on_super
end
end
test 'attribute_method?' do
test "attribute_method?" do
assert @target.attribute_method?(:title)
assert @target.attribute_method?(:title=)
assert_not @target.attribute_method?(:wibble)
end
test 'attribute_method? returns false if the table does not exist' do
@target.table_name = 'wibble'
test "attribute_method? returns false if the table does not exist" do
@target.table_name = "wibble"
assert_not @target.attribute_method?(:title)
end
test 'attribute_names on a new record' do
test "attribute_names on a new record" do
model = @target.new
assert_equal @target.column_names, model.attribute_names
end
test 'attribute_names on a queried record' do
test "attribute_names on a queried record" do
model = @target.last!
assert_equal @target.column_names, model.attribute_names
end
test 'attribute_names with a custom select' do
model = @target.select('id').last!
test "attribute_names with a custom select" do
model = @target.select("id").last!
assert_equal ['id'], model.attribute_names
assert_equal ["id"], model.attribute_names
# Sanity check, make sure other columns exist.
assert_not_equal ['id'], @target.column_names
assert_not_equal ["id"], @target.column_names
end
test 'came_from_user?' do
test "came_from_user?" do
model = @target.first
assert_not model.id_came_from_user?
@ -963,7 +963,7 @@ def some_method_that_is_not_on_super
assert model.id_came_from_user?
end
test 'accessed_fields' do
test "accessed_fields" do
model = @target.first
assert_equal [], model.accessed_fields
@ -977,7 +977,7 @@ def some_method_that_is_not_on_super
def new_topic_like_ar_class(&block)
klass = Class.new(ActiveRecord::Base) do
self.table_name = 'topics'
self.table_name = "topics"
class_eval(&block)
end

@ -1,10 +1,10 @@
require 'cases/helper'
require "cases/helper"
module ActiveRecord
class AttributeSetTest < ActiveRecord::TestCase
test "building a new set from raw attributes" do
builder = AttributeSet::Builder.new(foo: Type::Integer.new, bar: Type::Float.new)
attributes = builder.build_from_database(foo: '1.1', bar: '2.2')
attributes = builder.build_from_database(foo: "1.1", bar: "2.2")
assert_equal 1, attributes[:foo].value
assert_equal 2.2, attributes[:bar].value
@ -14,7 +14,7 @@ class AttributeSetTest < ActiveRecord::TestCase
test "building with custom types" do
builder = AttributeSet::Builder.new(foo: Type::Float.new)
attributes = builder.build_from_database({ foo: '3.3', bar: '4.4' }, { bar: Type::Integer.new })
attributes = builder.build_from_database({ foo: "3.3", bar: "4.4" }, { bar: Type::Integer.new })
assert_equal 3.3, attributes[:foo].value
assert_equal 4, attributes[:bar].value
@ -22,16 +22,16 @@ class AttributeSetTest < ActiveRecord::TestCase
test "[] returns a null object" do
builder = AttributeSet::Builder.new(foo: Type::Float.new)
attributes = builder.build_from_database(foo: '3.3')
attributes = builder.build_from_database(foo: "3.3")
assert_equal '3.3', attributes[:foo].value_before_type_cast
assert_equal "3.3", attributes[:foo].value_before_type_cast
assert_equal nil, attributes[:bar].value_before_type_cast
assert_equal :bar, attributes[:bar].name
end
test "duping creates a new hash, but does not dup the attributes" do
builder = AttributeSet::Builder.new(foo: Type::Integer.new, bar: Type::String.new)
attributes = builder.build_from_database(foo: 1, bar: 'foo')
attributes = builder.build_from_database(foo: 1, bar: "foo")
# Ensure the type cast value is cached
attributes[:foo].value
@ -39,17 +39,17 @@ class AttributeSetTest < ActiveRecord::TestCase
duped = attributes.dup
duped.write_from_database(:foo, 2)
duped[:bar].value << 'bar'
duped[:bar].value << "bar"
assert_equal 1, attributes[:foo].value
assert_equal 2, duped[:foo].value
assert_equal 'foobar', attributes[:bar].value
assert_equal 'foobar', duped[:bar].value
assert_equal "foobar", attributes[:bar].value
assert_equal "foobar", duped[:bar].value
end
test "deep_duping creates a new hash and dups each attribute" do
builder = AttributeSet::Builder.new(foo: Type::Integer.new, bar: Type::String.new)
attributes = builder.build_from_database(foo: 1, bar: 'foo')
attributes = builder.build_from_database(foo: 1, bar: "foo")
# Ensure the type cast value is cached
attributes[:foo].value
@ -57,12 +57,12 @@ class AttributeSetTest < ActiveRecord::TestCase
duped = attributes.deep_dup
duped.write_from_database(:foo, 2)
duped[:bar].value << 'bar'
duped[:bar].value << "bar"
assert_equal 1, attributes[:foo].value
assert_equal 2, duped[:foo].value
assert_equal 'foo', attributes[:bar].value
assert_equal 'foobar', duped[:bar].value
assert_equal "foo", attributes[:bar].value
assert_equal "foobar", duped[:bar].value
end
test "freezing cloned set does not freeze original" do
@ -77,7 +77,7 @@ class AttributeSetTest < ActiveRecord::TestCase
test "to_hash returns a hash of the type cast values" do
builder = AttributeSet::Builder.new(foo: Type::Integer.new, bar: Type::Float.new)
attributes = builder.build_from_database(foo: '1.1', bar: '2.2')
attributes = builder.build_from_database(foo: "1.1", bar: "2.2")
assert_equal({ foo: 1, bar: 2.2 }, attributes.to_hash)
assert_equal({ foo: 1, bar: 2.2 }, attributes.to_h)
@ -85,7 +85,7 @@ class AttributeSetTest < ActiveRecord::TestCase
test "to_hash maintains order" do
builder = AttributeSet::Builder.new(foo: Type::Integer.new, bar: Type::Float.new)
attributes = builder.build_from_database(foo: '2.2', bar: '3.3')
attributes = builder.build_from_database(foo: "2.2", bar: "3.3")
attributes[:bar]
hash = attributes.to_h
@ -95,9 +95,9 @@ class AttributeSetTest < ActiveRecord::TestCase
test "values_before_type_cast" do
builder = AttributeSet::Builder.new(foo: Type::Integer.new, bar: Type::Integer.new)
attributes = builder.build_from_database(foo: '1.1', bar: '2.2')
attributes = builder.build_from_database(foo: "1.1", bar: "2.2")
assert_equal({ foo: '1.1', bar: '2.2' }, attributes.values_before_type_cast)
assert_equal({ foo: "1.1", bar: "2.2" }, attributes.values_before_type_cast)
end
test "known columns are built with uninitialized attributes" do
@ -129,7 +129,7 @@ class AttributeSetTest < ActiveRecord::TestCase
test "fetch_value returns the value for the given initialized attribute" do
builder = AttributeSet::Builder.new(foo: Type::Integer.new, bar: Type::Float.new)
attributes = builder.build_from_database(foo: '1.1', bar: '2.2')
attributes = builder.build_from_database(foo: "1.1", bar: "2.2")
assert_equal 1, attributes.fetch_value(:foo)
assert_equal 2.2, attributes.fetch_value(:bar)
@ -150,8 +150,8 @@ class AttributeSetTest < ActiveRecord::TestCase
test "fetch_value uses the given block for uninitialized attributes" do
attributes = attributes_with_uninitialized_key
value = attributes.fetch_value(:bar) { |n| n.to_s + '!' }
assert_equal 'bar!', value
value = attributes.fetch_value(:bar) { |n| n.to_s + "!" }
assert_equal "bar!", value
end
test "fetch_value returns nil for uninitialized attributes if no block is given" do
@ -207,7 +207,7 @@ def assert_valid_value(*)
def attributes_with_uninitialized_key
builder = AttributeSet::Builder.new(foo: Type::Integer.new, bar: Type::Float.new)
builder.build_from_database(foo: '1.1')
builder.build_from_database(foo: "1.1")
end
test "freezing doesn't prevent the set from materializing" do

@ -1,4 +1,4 @@
require 'cases/helper'
require "cases/helper"
module ActiveRecord
class AttributeTest < ActiveRecord::TestCase
@ -11,91 +11,91 @@ class AttributeTest < ActiveRecord::TestCase
end
test "from_database + read type casts from database" do
@type.expect(:deserialize, 'type cast from database', ['a value'])
attribute = Attribute.from_database(nil, 'a value', @type)
@type.expect(:deserialize, "type cast from database", ["a value"])
attribute = Attribute.from_database(nil, "a value", @type)
type_cast_value = attribute.value
assert_equal 'type cast from database', type_cast_value
assert_equal "type cast from database", type_cast_value
end
test "from_user + read type casts from user" do
@type.expect(:cast, 'type cast from user', ['a value'])
attribute = Attribute.from_user(nil, 'a value', @type)
@type.expect(:cast, "type cast from user", ["a value"])
attribute = Attribute.from_user(nil, "a value", @type)
type_cast_value = attribute.value
assert_equal 'type cast from user', type_cast_value
assert_equal "type cast from user", type_cast_value
end
test "reading memoizes the value" do
@type.expect(:deserialize, 'from the database', ['whatever'])
attribute = Attribute.from_database(nil, 'whatever', @type)
@type.expect(:deserialize, "from the database", ["whatever"])
attribute = Attribute.from_database(nil, "whatever", @type)
type_cast_value = attribute.value
second_read = attribute.value
assert_equal 'from the database', type_cast_value
assert_equal "from the database", type_cast_value
assert_same type_cast_value, second_read
end
test "reading memoizes falsy values" do
@type.expect(:deserialize, false, ['whatever'])
attribute = Attribute.from_database(nil, 'whatever', @type)
@type.expect(:deserialize, false, ["whatever"])
attribute = Attribute.from_database(nil, "whatever", @type)
attribute.value
attribute.value
end
test "read_before_typecast returns the given value" do
attribute = Attribute.from_database(nil, 'raw value', @type)
attribute = Attribute.from_database(nil, "raw value", @type)
raw_value = attribute.value_before_type_cast
assert_equal 'raw value', raw_value
assert_equal "raw value", raw_value
end
test "from_database + read_for_database type casts to and from database" do
@type.expect(:deserialize, 'read from database', ['whatever'])
@type.expect(:serialize, 'ready for database', ['read from database'])
attribute = Attribute.from_database(nil, 'whatever', @type)
@type.expect(:deserialize, "read from database", ["whatever"])
@type.expect(:serialize, "ready for database", ["read from database"])
attribute = Attribute.from_database(nil, "whatever", @type)
serialize = attribute.value_for_database
assert_equal 'ready for database', serialize
assert_equal "ready for database", serialize
end
test "from_user + read_for_database type casts from the user to the database" do
@type.expect(:cast, 'read from user', ['whatever'])
@type.expect(:serialize, 'ready for database', ['read from user'])
attribute = Attribute.from_user(nil, 'whatever', @type)
@type.expect(:cast, "read from user", ["whatever"])
@type.expect(:serialize, "ready for database", ["read from user"])
attribute = Attribute.from_user(nil, "whatever", @type)
serialize = attribute.value_for_database
assert_equal 'ready for database', serialize
assert_equal "ready for database", serialize
end
test "duping dups the value" do
@type.expect(:deserialize, 'type cast', ['a value'])
attribute = Attribute.from_database(nil, 'a value', @type)
@type.expect(:deserialize, "type cast", ["a value"])
attribute = Attribute.from_database(nil, "a value", @type)
value_from_orig = attribute.value
value_from_clone = attribute.dup.value
value_from_orig << ' foo'
value_from_orig << " foo"
assert_equal 'type cast foo', value_from_orig
assert_equal 'type cast', value_from_clone
assert_equal "type cast foo", value_from_orig
assert_equal "type cast", value_from_clone
end
test "duping does not dup the value if it is not dupable" do
@type.expect(:deserialize, false, ['a value'])
attribute = Attribute.from_database(nil, 'a value', @type)
@type.expect(:deserialize, false, ["a value"])
attribute = Attribute.from_database(nil, "a value", @type)
assert_same attribute.value, attribute.dup.value
end
test "duping does not eagerly type cast if we have not yet type cast" do
attribute = Attribute.from_database(nil, 'a value', @type)
attribute = Attribute.from_database(nil, "a value", @type)
attribute.dup
end

@ -1,10 +1,10 @@
require 'cases/helper'
require "cases/helper"
class OverloadedType < ActiveRecord::Base
attribute :overloaded_float, :integer
attribute :overloaded_string_with_limit, :string, limit: 50
attribute :non_existent_decimal, :decimal
attribute :string_with_default, :string, default: 'the overloaded default'
attribute :string_with_default, :string, default: "the overloaded default"
end
class ChildOfOverloadedType < OverloadedType
@ -15,7 +15,7 @@ class GrandchildOfOverloadedType < ChildOfOverloadedType
end
class UnoverloadedType < ActiveRecord::Base
self.table_name = 'overloaded_types'
self.table_name = "overloaded_types"
end
module ActiveRecord
@ -44,14 +44,14 @@ class CustomPropertiesTest < ActiveRecord::TestCase
end
test "properties assigned in constructor" do
data = OverloadedType.new(overloaded_float: '3.3')
data = OverloadedType.new(overloaded_float: "3.3")
assert_equal 3, data.overloaded_float
end
test "overloaded properties with limit" do
assert_equal 50, OverloadedType.type_for_attribute('overloaded_string_with_limit').limit
assert_equal 255, UnoverloadedType.type_for_attribute('overloaded_string_with_limit').limit
assert_equal 50, OverloadedType.type_for_attribute("overloaded_string_with_limit").limit
assert_equal 255, UnoverloadedType.type_for_attribute("overloaded_string_with_limit").limit
end
test "nonexistent attribute" do
@ -65,7 +65,7 @@ class CustomPropertiesTest < ActiveRecord::TestCase
test "model with nonexistent attribute with default value can be saved" do
klass = Class.new(OverloadedType) do
attribute :non_existent_string_with_default, :string, default: 'nonexistent'
attribute :non_existent_string_with_default, :string, default: "nonexistent"
end
model = klass.new
@ -76,22 +76,22 @@ class CustomPropertiesTest < ActiveRecord::TestCase
data = OverloadedType.new
unoverloaded_data = UnoverloadedType.new
assert_equal 'the overloaded default', data.string_with_default
assert_equal 'the original default', unoverloaded_data.string_with_default
assert_equal "the overloaded default", data.string_with_default
assert_equal "the original default", unoverloaded_data.string_with_default
end
test "defaults are not touched on the columns" do
assert_equal 'the original default', OverloadedType.columns_hash['string_with_default'].default
assert_equal "the original default", OverloadedType.columns_hash["string_with_default"].default
end
test "children inherit custom properties" do
data = ChildOfOverloadedType.new(overloaded_float: '4.4')
data = ChildOfOverloadedType.new(overloaded_float: "4.4")
assert_equal 4, data.overloaded_float
end
test "children can override parents" do
data = GrandchildOfOverloadedType.new(overloaded_float: '4.4')
data = GrandchildOfOverloadedType.new(overloaded_float: "4.4")
assert_equal 4.4, data.overloaded_float
end
@ -106,13 +106,13 @@ class CustomPropertiesTest < ActiveRecord::TestCase
assert_equal 6, klass.attribute_types.length
assert_equal 6, klass.column_defaults.length
assert_not klass.attribute_types.include?('wibble')
assert_not klass.attribute_types.include?("wibble")
klass.attribute :wibble, Type::Value.new
assert_equal 7, klass.attribute_types.length
assert_equal 7, klass.column_defaults.length
assert klass.attribute_types.include?('wibble')
assert klass.attribute_types.include?("wibble")
end
test "the given default value is cast from user" do

@ -1,55 +1,55 @@
require 'cases/helper'
require 'models/bird'
require 'models/comment'
require 'models/company'
require 'models/customer'
require 'models/developer'
require 'models/computer'
require 'models/invoice'
require 'models/line_item'
require 'models/order'
require 'models/parrot'
require 'models/person'
require 'models/pirate'
require 'models/post'
require 'models/reader'
require 'models/ship'
require 'models/ship_part'
require 'models/tag'
require 'models/tagging'
require 'models/treasure'
require 'models/eye'
require 'models/electron'
require 'models/molecule'
require 'models/member'
require 'models/member_detail'
require 'models/organization'
require 'models/guitar'
require 'models/tuning_peg'
require "cases/helper"
require "models/bird"
require "models/comment"
require "models/company"
require "models/customer"
require "models/developer"
require "models/computer"
require "models/invoice"
require "models/line_item"
require "models/order"
require "models/parrot"
require "models/person"
require "models/pirate"
require "models/post"
require "models/reader"
require "models/ship"
require "models/ship_part"
require "models/tag"
require "models/tagging"
require "models/treasure"
require "models/eye"
require "models/electron"
require "models/molecule"
require "models/member"
require "models/member_detail"
require "models/organization"
require "models/guitar"
require "models/tuning_peg"
class TestAutosaveAssociationsInGeneral < ActiveRecord::TestCase
def test_autosave_validation
person = Class.new(ActiveRecord::Base) {
self.table_name = 'people'
self.table_name = "people"
validate :should_be_cool, :on => :create
def self.name; 'Person'; end
def self.name; "Person"; end
private
def should_be_cool
unless self.first_name == 'cool'
unless self.first_name == "cool"
errors.add :first_name, "not cool"
end
end
}
reference = Class.new(ActiveRecord::Base) {
self.table_name = "references"
def self.name; 'Reference'; end
def self.name; "Reference"; end
belongs_to :person, autosave: true, anonymous_class: person
}
u = person.create!(first_name: 'cool')
u.update_attributes!(first_name: 'nah') # still valid because validation only applies on 'create'
u = person.create!(first_name: "cool")
u.update_attributes!(first_name: "nah") # still valid because validation only applies on 'create'
assert reference.create!(person: u).persisted?
end
@ -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
@ -179,7 +179,7 @@ def test_assignment_before_either_saved
def test_not_resaved_when_unchanged
firm = Firm.all.merge!(:includes => :account).first
firm.name += '-changed'
firm.name += "-changed"
assert_queries(1) { firm.save! }
firm = Firm.first
@ -196,21 +196,21 @@ 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
def test_callbacks_firing_order_on_update
eye = Eye.create(iris_attributes: {color: 'honey'})
eye.update(iris_attributes: {color: 'green'})
eye = Eye.create(iris_attributes: {color: "honey"})
eye.update(iris_attributes: {color: "green"})
assert_equal [true, false], eye.after_update_callbacks_stack
end
def test_callbacks_firing_order_on_save
eye = Eye.create(iris_attributes: {color: 'honey'})
eye = Eye.create(iris_attributes: {color: "honey"})
assert_equal [false, false], eye.after_save_callbacks_stack
eye.update(iris_attributes: {color: 'blue'})
eye.update(iris_attributes: {color: "blue"})
assert_equal [false, false, false, false], eye.after_save_callbacks_stack
end
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
@ -388,7 +388,7 @@ def test_validation_does_not_validate_stale_association_target
class TestDefaultAutosaveAssociationOnAHasManyAssociationWithAcceptsNestedAttributes < ActiveRecord::TestCase
def test_invalid_adding_with_nested_attributes
molecule = Molecule.new
valid_electron = Electron.new(name: 'electron')
valid_electron = Electron.new(name: "electron")
invalid_electron = Electron.new
molecule.electrons = [valid_electron, invalid_electron]
@ -396,7 +396,7 @@ def test_invalid_adding_with_nested_attributes
assert_not invalid_electron.valid?
assert valid_electron.valid?
assert_not molecule.persisted?, 'Molecule should not be persisted when its electrons are invalid'
assert_not molecule.persisted?, "Molecule should not be persisted when its electrons are invalid"
end
def test_errors_should_be_indexed_when_passed_as_array
@ -419,7 +419,7 @@ def test_errors_should_be_indexed_when_global_flag_is_set
ActiveRecord::Base.index_nested_attribute_errors = true
molecule = Molecule.new
valid_electron = Electron.new(name: 'electron')
valid_electron = Electron.new(name: "electron")
invalid_electron = Electron.new
molecule.electrons = [valid_electron, invalid_electron]
@ -435,7 +435,7 @@ def test_errors_should_be_indexed_when_global_flag_is_set
def test_errors_details_should_be_set
molecule = Molecule.new
valid_electron = Electron.new(name: 'electron')
valid_electron = Electron.new(name: "electron")
invalid_electron = Electron.new
molecule.electrons = [valid_electron, invalid_electron]
@ -466,7 +466,7 @@ def test_errors_details_should_be_indexed_when_global_flag_is_set
ActiveRecord::Base.index_nested_attribute_errors = true
molecule = Molecule.new
valid_electron = Electron.new(name: 'electron')
valid_electron = Electron.new(name: "electron")
invalid_electron = Electron.new
molecule.electrons = [valid_electron, invalid_electron]
@ -482,7 +482,7 @@ def test_errors_details_should_be_indexed_when_global_flag_is_set
def test_valid_adding_with_nested_attributes
molecule = Molecule.new
valid_electron = Electron.new(name: 'electron')
valid_electron = Electron.new(name: "electron")
molecule.electrons = [valid_electron]
molecule.save
@ -602,7 +602,7 @@ def test_build_before_save
new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.build("name" => "Another Client") }
assert !company.clients_of_firm.loaded?
company.name += '-changed'
company.name += "-changed"
assert_queries(2) { assert company.save }
assert new_client.persisted?
assert_equal 3, company.clients_of_firm.reload.size
@ -612,7 +612,7 @@ def test_build_many_before_save
company = companies(:first_firm)
assert_no_queries(ignore_none: false) { company.clients_of_firm.build([{"name" => "Another Client"}, {"name" => "Another Client II"}]) }
company.name += '-changed'
company.name += "-changed"
assert_queries(3) { assert company.save }
assert_equal 4, company.clients_of_firm.reload.size
end
@ -622,7 +622,7 @@ def test_build_via_block_before_save
new_client = assert_no_queries(ignore_none: false) { company.clients_of_firm.build {|client| client.name = "Another Client" } }
assert !company.clients_of_firm.loaded?
company.name += '-changed'
company.name += "-changed"
assert_queries(2) { assert company.save }
assert new_client.persisted?
assert_equal 3, company.clients_of_firm.reload.size
@ -636,7 +636,7 @@ def test_build_many_via_block_before_save
end
end
company.name += '-changed'
company.name += "-changed"
assert_queries(3) { assert company.save }
assert_equal 4, company.clients_of_firm.reload.size
end
@ -715,8 +715,8 @@ def test_autosave_new_record_on_has_many_can_be_disabled_per_relationship
end
def test_autosave_new_record_with_after_create_callback
post = PostWithAfterCreateCallback.new(title: 'Captain Murphy', body: 'is back')
post.comments.build(body: 'foo')
post = PostWithAfterCreateCallback.new(title: "Captain Murphy", body: "is back")
post.comments.build(body: "foo")
post.save!
assert_not_nil post.author_id
@ -728,7 +728,7 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
setup do
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@ship = @pirate.create_ship(:name => 'Nights Dirty Lightning')
@ship = @pirate.create_ship(:name => "Nights Dirty Lightning")
end
teardown do
@ -764,12 +764,12 @@ def test_should_destroy_a_child_association_as_part_of_the_save_transaction_if_i
end
def test_should_skip_validation_on_a_child_association_if_marked_for_destruction
@pirate.ship.name = ''
@pirate.ship.name = ""
assert !@pirate.valid?
@pirate.ship.mark_for_destruction
@pirate.ship.expects(:valid?).never
assert_difference('Ship.count', -1) { @pirate.save! }
assert_difference("Ship.count", -1) { @pirate.save! }
end
def test_a_child_marked_for_destruction_should_not_be_destroyed_twice
@ -787,7 +787,7 @@ class << @pirate.ship
def save(*args)
super
destroy
raise 'Oh noes!'
raise "Oh noes!"
end
end
@ -824,12 +824,12 @@ def test_should_destroy_a_parent_association_as_part_of_the_save_transaction_if_
end
def test_should_skip_validation_on_a_parent_association_if_marked_for_destruction
@ship.pirate.catchphrase = ''
@ship.pirate.catchphrase = ""
assert !@ship.valid?
@ship.pirate.mark_for_destruction
@ship.pirate.expects(:valid?).never
assert_difference('Pirate.count', -1) { @ship.save! }
assert_difference("Pirate.count", -1) { @ship.save! }
end
def test_a_parent_marked_for_destruction_should_not_be_destroyed_twice
@ -847,7 +847,7 @@ class << @ship.pirate
def save(*args)
super
destroy
raise 'Oh noes!'
raise "Oh noes!"
end
end
@ -859,11 +859,11 @@ def save(*args)
def test_should_save_changed_child_objects_if_parent_is_saved
@pirate = @ship.create_pirate(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@parrot = @pirate.parrots.create!(:name => 'Posideons Killer')
@parrot = @pirate.parrots.create!(:name => "Posideons Killer")
@parrot.name = "NewName"
@ship.save
assert_equal 'NewName', @parrot.reload.name
assert_equal "NewName", @parrot.reload.name
end
def test_should_destroy_has_many_as_part_of_the_save_transaction_if_they_were_marked_for_destruction
@ -893,7 +893,7 @@ def test_should_not_resave_destroyed_association
def test_should_skip_validation_on_has_many_if_marked_for_destruction
2.times { |i| @pirate.birds.create!(:name => "birds_#{i}") }
@pirate.birds.each { |bird| bird.name = '' }
@pirate.birds.each { |bird| bird.name = "" }
assert !@pirate.valid?
@pirate.birds.each do |bird|
@ -906,7 +906,7 @@ def test_should_skip_validation_on_has_many_if_marked_for_destruction
def test_should_skip_validation_on_has_many_if_destroyed
@pirate.birds.create!(:name => "birds_1")
@pirate.birds.each { |bird| bird.name = '' }
@pirate.birds.each { |bird| bird.name = "" }
assert !@pirate.valid?
@pirate.birds.each(&:destroy)
@ -931,7 +931,7 @@ def test_should_rollback_destructions_if_an_exception_occurred_while_saving_has_
class << before.last
def destroy(*args)
super
raise 'Oh noes!'
raise "Oh noes!"
end
end
@ -1017,7 +1017,7 @@ def test_should_destroy_habtm_as_part_of_the_save_transaction_if_they_were_marke
def test_should_skip_validation_on_habtm_if_marked_for_destruction
2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") }
@pirate.parrots.each { |parrot| parrot.name = '' }
@pirate.parrots.each { |parrot| parrot.name = "" }
assert !@pirate.valid?
@pirate.parrots.each do |parrot|
@ -1032,7 +1032,7 @@ def test_should_skip_validation_on_habtm_if_marked_for_destruction
def test_should_skip_validation_on_habtm_if_destroyed
@pirate.parrots.create!(:name => "parrots_1")
@pirate.parrots.each { |parrot| parrot.name = '' }
@pirate.parrots.each { |parrot| parrot.name = "" }
assert !@pirate.valid?
@pirate.parrots.each(&:destroy)
@ -1059,7 +1059,7 @@ def test_should_rollback_destructions_if_an_exception_occurred_while_saving_habt
class << @pirate.association(:parrots)
def destroy(*args)
super
raise 'Oh noes!'
raise "Oh noes!"
end
end
@ -1109,20 +1109,20 @@ 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')
@ship = @pirate.create_ship(:name => "Nights Dirty Lightning")
end
def test_should_still_work_without_an_associated_model
@ship.destroy
@pirate.reload.catchphrase = "Arr"
@pirate.save
assert_equal 'Arr', @pirate.reload.catchphrase
assert_equal "Arr", @pirate.reload.catchphrase
end
def test_should_automatically_save_the_associated_model
@pirate.ship.name = 'The Vile Insanity'
@pirate.ship.name = "The Vile Insanity"
@pirate.save
assert_equal 'The Vile Insanity', @pirate.reload.ship.name
assert_equal "The Vile Insanity", @pirate.reload.ship.name
end
def test_changed_for_autosave_should_handle_cycles
@ -1136,13 +1136,13 @@ def test_changed_for_autosave_should_handle_cycles
end
def test_should_automatically_save_bang_the_associated_model
@pirate.ship.name = 'The Vile Insanity'
@pirate.ship.name = "The Vile Insanity"
@pirate.save!
assert_equal 'The Vile Insanity', @pirate.reload.ship.name
assert_equal "The Vile Insanity", @pirate.reload.ship.name
end
def test_should_automatically_validate_the_associated_model
@pirate.ship.name = ''
@pirate.ship.name = ""
assert @pirate.invalid?
assert @pirate.errors[:"ship.name"].any?
end
@ -1169,23 +1169,23 @@ def test_should_not_ignore_different_error_messages_on_the_same_attribute
end
def test_should_still_allow_to_bypass_validations_on_the_associated_model
@pirate.catchphrase = ''
@pirate.ship.name = ''
@pirate.catchphrase = ""
@pirate.ship.name = ""
@pirate.save(:validate => false)
# Oracle saves empty string as NULL
if current_adapter?(:OracleAdapter)
assert_equal [nil, nil], [@pirate.reload.catchphrase, @pirate.ship.name]
else
assert_equal ['', ''], [@pirate.reload.catchphrase, @pirate.ship.name]
assert_equal ["", ""], [@pirate.reload.catchphrase, @pirate.ship.name]
end
end
def test_should_allow_to_bypass_validations_on_associated_models_at_any_depth
2.times { |i| @pirate.ship.parts.create!(:name => "part #{i}") }
@pirate.catchphrase = ''
@pirate.ship.name = ''
@pirate.ship.parts.each { |part| part.name = '' }
@pirate.catchphrase = ""
@pirate.ship.name = ""
@pirate.ship.parts.each { |part| part.name = "" }
@pirate.save(:validate => false)
values = [@pirate.reload.catchphrase, @pirate.ship.name, *@pirate.ship.parts.map(&:name)]
@ -1193,24 +1193,24 @@ def test_should_allow_to_bypass_validations_on_associated_models_at_any_depth
if current_adapter?(:OracleAdapter)
assert_equal [nil, nil, nil, nil], values
else
assert_equal ['', '', '', ''], values
assert_equal ["", "", "", ""], values
end
end
def test_should_still_raise_an_ActiveRecordRecord_Invalid_exception_if_we_want_that
@pirate.ship.name = ''
@pirate.ship.name = ""
assert_raise(ActiveRecord::RecordInvalid) do
@pirate.save!
end
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
assert_no_difference 'Ship.count' do
assert_no_difference "Pirate.count" do
assert_no_difference "Ship.count" do
assert !pirate.save
end
end
@ -1219,14 +1219,14 @@ def test_should_not_save_and_return_false_if_a_callback_cancelled_saving
def test_should_rollback_any_changes_if_an_exception_occurred_while_saving
before = [@pirate.catchphrase, @pirate.ship.name]
@pirate.catchphrase = 'Arr'
@pirate.ship.name = 'The Vile Insanity'
@pirate.catchphrase = "Arr"
@pirate.ship.name = "The Vile Insanity"
# Stub the save method of the @pirate.ship instance to raise an exception
class << @pirate.ship
def save(*args)
super
raise 'Oh noes!'
raise "Oh noes!"
end
end
@ -1235,7 +1235,7 @@ def save(*args)
end
def test_should_not_load_the_associated_model
assert_queries(1) { @pirate.catchphrase = 'Arr'; @pirate.save! }
assert_queries(1) { @pirate.catchphrase = "Arr"; @pirate.save! }
end
def test_mark_for_destruction_is_ignored_without_autosave_true
@ -1260,7 +1260,7 @@ def test_should_not_has_one_through_model
class << @member.organization
def save(*args)
super
raise 'Oh noes!'
raise "Oh noes!"
end
end
assert_nothing_raised { @member.save }
@ -1272,7 +1272,7 @@ class TestAutosaveAssociationOnABelongsToAssociation < ActiveRecord::TestCase
def setup
super
@ship = Ship.create(:name => 'Nights Dirty Lightning')
@ship = Ship.create(:name => "Nights Dirty Lightning")
@pirate = @ship.create_pirate(:catchphrase => "Don' botharrr talkin' like one, savvy?")
end
@ -1280,23 +1280,23 @@ def test_should_still_work_without_an_associated_model
@pirate.destroy
@ship.reload.name = "The Vile Insanity"
@ship.save
assert_equal 'The Vile Insanity', @ship.reload.name
assert_equal "The Vile Insanity", @ship.reload.name
end
def test_should_automatically_save_the_associated_model
@ship.pirate.catchphrase = 'Arr'
@ship.pirate.catchphrase = "Arr"
@ship.save
assert_equal 'Arr', @ship.reload.pirate.catchphrase
assert_equal "Arr", @ship.reload.pirate.catchphrase
end
def test_should_automatically_save_bang_the_associated_model
@ship.pirate.catchphrase = 'Arr'
@ship.pirate.catchphrase = "Arr"
@ship.save!
assert_equal 'Arr', @ship.reload.pirate.catchphrase
assert_equal "Arr", @ship.reload.pirate.catchphrase
end
def test_should_automatically_validate_the_associated_model
@ship.pirate.catchphrase = ''
@ship.pirate.catchphrase = ""
assert @ship.invalid?
assert @ship.errors[:"pirate.catchphrase"].any?
end
@ -1310,31 +1310,31 @@ def test_should_merge_errors_on_the_associated_model_onto_the_parent_even_if_it_
end
def test_should_still_allow_to_bypass_validations_on_the_associated_model
@ship.pirate.catchphrase = ''
@ship.name = ''
@ship.pirate.catchphrase = ""
@ship.name = ""
@ship.save(:validate => false)
# Oracle saves empty string as NULL
if current_adapter?(:OracleAdapter)
assert_equal [nil, nil], [@ship.reload.name, @ship.pirate.catchphrase]
else
assert_equal ['', ''], [@ship.reload.name, @ship.pirate.catchphrase]
assert_equal ["", ""], [@ship.reload.name, @ship.pirate.catchphrase]
end
end
def test_should_still_raise_an_ActiveRecordRecord_Invalid_exception_if_we_want_that
@ship.pirate.catchphrase = ''
@ship.pirate.catchphrase = ""
assert_raise(ActiveRecord::RecordInvalid) do
@ship.save!
end
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
assert_no_difference 'Pirate.count' do
assert_no_difference "Ship.count" do
assert_no_difference "Pirate.count" do
assert !ship.save
end
end
@ -1343,14 +1343,14 @@ def test_should_not_save_and_return_false_if_a_callback_cancelled_saving
def test_should_rollback_any_changes_if_an_exception_occurred_while_saving
before = [@ship.pirate.catchphrase, @ship.name]
@ship.pirate.catchphrase = 'Arr'
@ship.name = 'The Vile Insanity'
@ship.pirate.catchphrase = "Arr"
@ship.name = "The Vile Insanity"
# Stub the save method of the @ship.pirate instance to raise an exception
class << @ship.pirate
def save(*args)
super
raise 'Oh noes!'
raise "Oh noes!"
end
end
@ -1359,13 +1359,13 @@ def save(*args)
end
def test_should_not_load_the_associated_model
assert_queries(1) { @ship.name = 'The Vile Insanity'; @ship.save! }
assert_queries(1) { @ship.name = "The Vile Insanity"; @ship.save! }
end
end
module AutosaveAssociationOnACollectionAssociationTests
def test_should_automatically_save_the_associated_models
new_names = ['Grace OMalley', 'Privateers Greed']
new_names = ["Grace OMalley", "Privateers Greed"]
@pirate.send(@association_name).each_with_index { |child, i| child.name = new_names[i] }
@pirate.save
@ -1373,7 +1373,7 @@ def test_should_automatically_save_the_associated_models
end
def test_should_automatically_save_bang_the_associated_models
new_names = ['Grace OMalley', 'Privateers Greed']
new_names = ["Grace OMalley", "Privateers Greed"]
@pirate.send(@association_name).each_with_index { |child, i| child.name = new_names[i] }
@pirate.save!
@ -1391,7 +1391,7 @@ def test_should_update_children_when_autosave_is_true_and_parent_is_new_but_chil
end
def test_should_automatically_validate_the_associated_models
@pirate.send(@association_name).each { |child| child.name = '' }
@pirate.send(@association_name).each { |child| child.name = "" }
assert !@pirate.valid?
assert_equal ["can't be blank"], @pirate.errors["#{@association_name}.name"]
@ -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"]
@ -1411,7 +1411,7 @@ def test_should_default_invalid_error_from_i18n
{ @associated_model_name.to_s.to_sym => { blank: "cannot be blank" } }
}})
@pirate.send(@association_name).build(name: '')
@pirate.send(@association_name).build(name: "")
assert !@pirate.valid?
assert_equal ["cannot be blank"], @pirate.errors["#{@association_name}.name"]
@ -1422,7 +1422,7 @@ def test_should_default_invalid_error_from_i18n
end
def test_should_merge_errors_on_the_associated_models_onto_the_parent_even_if_it_is_not_valid
@pirate.send(@association_name).each { |child| child.name = '' }
@pirate.send(@association_name).each { |child| child.name = "" }
@pirate.catchphrase = nil
assert !@pirate.valid?
@ -1431,8 +1431,8 @@ def test_should_merge_errors_on_the_associated_models_onto_the_parent_even_if_it
end
def test_should_allow_to_bypass_validations_on_the_associated_models_on_update
@pirate.catchphrase = ''
@pirate.send(@association_name).each { |child| child.name = '' }
@pirate.catchphrase = ""
@pirate.send(@association_name).each { |child| child.name = "" }
assert @pirate.save(:validate => false)
# Oracle saves empty string as NULL
@ -1443,7 +1443,7 @@ def test_should_allow_to_bypass_validations_on_the_associated_models_on_update
@pirate.send(@association_name).last.name
]
else
assert_equal ['', '', ''], [
assert_equal ["", "", ""], [
@pirate.reload.catchphrase,
@pirate.send(@association_name).first.name,
@pirate.send(@association_name).last.name
@ -1466,19 +1466,19 @@ def test_should_allow_to_bypass_validations_on_the_associated_models_on_create
end
def test_should_not_save_and_return_false_if_a_callback_cancelled_saving_in_either_create_or_update
@pirate.catchphrase = 'Changed'
@child_1.name = 'Changed'
@pirate.catchphrase = "Changed"
@child_1.name = "Changed"
@child_1.cancel_save_from_callback = true
assert !@pirate.save
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
assert_no_difference "Pirate.count" do
assert_no_difference "#{new_child.class.name}.count" do
assert !new_pirate.save
end
@ -1487,16 +1487,16 @@ def test_should_not_save_and_return_false_if_a_callback_cancelled_saving_in_eith
def test_should_rollback_any_changes_if_an_exception_occurred_while_saving
before = [@pirate.catchphrase, *@pirate.send(@association_name).map(&:name)]
new_names = ['Grace OMalley', 'Privateers Greed']
new_names = ["Grace OMalley", "Privateers Greed"]
@pirate.catchphrase = 'Arr'
@pirate.catchphrase = "Arr"
@pirate.send(@association_name).each_with_index { |child, i| child.name = new_names[i] }
# Stub the save method of the first child instance to raise an exception
class << @pirate.send(@association_name).first
def save(*args)
super
raise 'Oh noes!'
raise "Oh noes!"
end
end
@ -1505,20 +1505,20 @@ def save(*args)
end
def test_should_still_raise_an_ActiveRecordRecord_Invalid_exception_if_we_want_that
@pirate.send(@association_name).each { |child| child.name = '' }
@pirate.send(@association_name).each { |child| child.name = "" }
assert_raise(ActiveRecord::RecordInvalid) do
@pirate.save!
end
end
def test_should_not_load_the_associated_models_if_they_were_not_loaded_yet
assert_queries(1) { @pirate.catchphrase = 'Arr'; @pirate.save! }
assert_queries(1) { @pirate.catchphrase = "Arr"; @pirate.save! }
@pirate.send(@association_name).load_target
assert_queries(3) do
@pirate.catchphrase = 'Yarr'
new_names = ['Grace OMalley', 'Privateers Greed']
@pirate.catchphrase = "Yarr"
new_names = ["Grace OMalley", "Privateers Greed"]
@pirate.send(@association_name).each_with_index { |child, i| child.name = new_names[i] }
@pirate.save!
end
@ -1534,8 +1534,8 @@ def setup
@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')
@child_1 = @pirate.birds.create(:name => "Posideons Killer")
@child_2 = @pirate.birds.create(:name => "Killer bandita Dionne")
end
include AutosaveAssociationOnACollectionAssociationTests
@ -1551,8 +1551,8 @@ def setup
@habtm = true
@pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?")
@child_1 = @pirate.parrots.create(name: 'Posideons Killer')
@child_2 = @pirate.parrots.create(name: 'Killer bandita Dionne')
@child_1 = @pirate.parrots.create(name: "Posideons Killer")
@child_2 = @pirate.parrots.create(name: "Killer bandita Dionne")
end
include AutosaveAssociationOnACollectionAssociationTests
@ -1568,8 +1568,8 @@ def setup
@habtm = true
@pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?")
@child_1 = @pirate.parrots.create(name: 'Posideons Killer')
@child_2 = @pirate.parrots.create(name: 'Killer bandita Dionne')
@child_1 = @pirate.parrots.create(name: "Posideons Killer")
@child_2 = @pirate.parrots.create(name: "Killer bandita Dionne")
end
include AutosaveAssociationOnACollectionAssociationTests
@ -1581,12 +1581,12 @@ class TestAutosaveAssociationValidationsOnAHasManyAssociation < ActiveRecord::Te
def setup
super
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@pirate.birds.create(:name => 'cookoo')
@pirate.birds.create(:name => "cookoo")
end
test "should automatically validate associations" do
assert @pirate.valid?
@pirate.birds.each { |bird| bird.name = '' }
@pirate.birds.each { |bird| bird.name = "" }
assert !@pirate.valid?
end
@ -1598,19 +1598,19 @@ class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::Tes
def setup
super
@pirate = Pirate.create(:catchphrase => "Don' botharrr talkin' like one, savvy?")
@pirate.create_ship(:name => 'titanic')
@pirate.create_ship(:name => "titanic")
super
end
test "should automatically validate associations with :validate => true" do
assert @pirate.valid?
@pirate.ship.name = ''
@pirate.ship.name = ""
assert !@pirate.valid?
end
test "should not automatically add validate associations without :validate => true" do
assert @pirate.valid?
@pirate.non_validated_ship.name = ''
@pirate.non_validated_ship.name = ""
assert @pirate.valid?
end
end
@ -1625,13 +1625,13 @@ def setup
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
@ -1646,15 +1646,15 @@ def setup
test "should automatically validate associations with :validate => true" do
assert @pirate.valid?
@pirate.parrots = [ Parrot.new(:name => 'popuga') ]
@pirate.parrots.each { |parrot| parrot.name = '' }
@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.each { |parrot| parrot.name = '' }
@pirate.non_validated_parrots = [ Parrot.new(:name => "popuga") ]
@pirate.non_validated_parrots.each { |parrot| parrot.name = "" }
assert @pirate.valid?
end
end

@ -1,30 +1,30 @@
require "cases/helper"
require 'models/post'
require 'models/author'
require 'models/topic'
require 'models/reply'
require 'models/category'
require 'models/company'
require 'models/customer'
require 'models/developer'
require 'models/computer'
require 'models/project'
require 'models/default'
require 'models/auto_id'
require 'models/boolean'
require 'models/column_name'
require 'models/subscriber'
require 'models/comment'
require 'models/minimalistic'
require 'models/warehouse_thing'
require 'models/parrot'
require 'models/person'
require 'models/edge'
require 'models/joke'
require 'models/bird'
require 'models/car'
require 'models/bulb'
require 'concurrent/atomic/count_down_latch'
require "models/post"
require "models/author"
require "models/topic"
require "models/reply"
require "models/category"
require "models/company"
require "models/customer"
require "models/developer"
require "models/computer"
require "models/project"
require "models/default"
require "models/auto_id"
require "models/boolean"
require "models/column_name"
require "models/subscriber"
require "models/comment"
require "models/minimalistic"
require "models/warehouse_thing"
require "models/parrot"
require "models/person"
require "models/edge"
require "models/joke"
require "models/bird"
require "models/car"
require "models/bulb"
require "concurrent/atomic/count_down_latch"
class FirstAbstractClass < ActiveRecord::Base
self.abstract_class = true
@ -73,17 +73,17 @@ def setup
end
class BasicsTest < ActiveRecord::TestCase
fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts
fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, "warehouse-things", :authors, :categorizations, :categories, :posts
def test_column_names_are_escaped
conn = ActiveRecord::Base.connection
classname = conn.class.name[/[^:]*$/]
badchar = {
'SQLite3Adapter' => '"',
'Mysql2Adapter' => '`',
'PostgreSQLAdapter' => '"',
'OracleAdapter' => '"',
'FbAdapter' => '"'
"SQLite3Adapter" => '"',
"Mysql2Adapter" => "`",
"PostgreSQLAdapter" => '"',
"OracleAdapter" => '"',
"FbAdapter" => '"'
}.fetch(classname) {
raise "need a bad char for #{classname}"
}
@ -100,7 +100,7 @@ def test_column_names_are_escaped
def test_columns_should_obey_set_primary_key
pk = Subscriber.columns_hash[Subscriber.primary_key]
assert_equal 'nick', pk.name, 'nick should be primary key'
assert_equal "nick", pk.name, "nick should be primary key"
end
def test_primary_key_with_no_id
@ -164,17 +164,17 @@ def test_preserving_date_objects
def test_previously_changed
topic = Topic.first
topic.title = '<3<3<3'
topic.title = "<3<3<3"
assert_equal({}, topic.previous_changes)
topic.save!
expected = ["The First Topic", "<3<3<3"]
assert_equal(expected, topic.previous_changes['title'])
assert_equal(expected, topic.previous_changes["title"])
end
def test_previously_changed_dup
topic = Topic.first
topic.title = '<3<3<3'
topic.title = "<3<3<3"
topic.save!
t2 = topic.dup
@ -211,7 +211,7 @@ def test_preserving_time_objects_with_local_time_conversion_to_default_timezone_
with_env_tz eastern_time_zone do
with_timezone_config default: :utc do
time = Time.local(2000)
topic = Topic.create('written_on' => time)
topic = Topic.create("written_on" => time)
saved_time = Topic.find(topic.id).reload.written_on
assert_equal time, saved_time
assert_equal [0, 0, 0, 1, 1, 2000, 6, 1, false, "EST"], time.to_a
@ -223,9 +223,9 @@ def test_preserving_time_objects_with_local_time_conversion_to_default_timezone_
def test_preserving_time_objects_with_time_with_zone_conversion_to_default_timezone_utc
with_env_tz eastern_time_zone do
with_timezone_config default: :utc do
Time.use_zone 'Central Time (US & Canada)' do
Time.use_zone "Central Time (US & Canada)" do
time = Time.zone.local(2000)
topic = Topic.create('written_on' => time)
topic = Topic.create("written_on" => time)
saved_time = Topic.find(topic.id).reload.written_on
assert_equal time, saved_time
assert_equal [0, 0, 0, 1, 1, 2000, 6, 1, false, "CST"], time.to_a
@ -239,7 +239,7 @@ def test_preserving_time_objects_with_utc_time_conversion_to_default_timezone_lo
with_env_tz eastern_time_zone do
with_timezone_config default: :local do
time = Time.utc(2000)
topic = Topic.create('written_on' => time)
topic = Topic.create("written_on" => time)
saved_time = Topic.find(topic.id).reload.written_on
assert_equal time, saved_time
assert_equal [0, 0, 0, 1, 1, 2000, 6, 1, false, "UTC"], time.to_a
@ -251,9 +251,9 @@ def test_preserving_time_objects_with_utc_time_conversion_to_default_timezone_lo
def test_preserving_time_objects_with_time_with_zone_conversion_to_default_timezone_local
with_env_tz eastern_time_zone do
with_timezone_config default: :local do
Time.use_zone 'Central Time (US & Canada)' do
Time.use_zone "Central Time (US & Canada)" do
time = Time.zone.local(2000)
topic = Topic.create('written_on' => time)
topic = Topic.create("written_on" => time)
saved_time = Topic.find(topic.id).reload.written_on
assert_equal time, saved_time
assert_equal [0, 0, 0, 1, 1, 2000, 6, 1, false, "CST"], time.to_a
@ -295,27 +295,27 @@ def test_initialize_with_invalid_attribute
end
def test_create_after_initialize_without_block
cb = CustomBulb.create(:name => 'Dude')
assert_equal('Dude', cb.name)
cb = CustomBulb.create(:name => "Dude")
assert_equal("Dude", cb.name)
assert_equal(true, cb.frickinawesome)
end
def test_create_after_initialize_with_block
cb = CustomBulb.create {|c| c.name = 'Dude' }
assert_equal('Dude', cb.name)
cb = CustomBulb.create {|c| c.name = "Dude" }
assert_equal("Dude", cb.name)
assert_equal(true, cb.frickinawesome)
end
def test_create_after_initialize_with_array_param
cbs = CustomBulb.create([{ name: 'Dude' }, { name: 'Bob' }])
assert_equal 'Dude', cbs[0].name
assert_equal 'Bob', cbs[1].name
cbs = CustomBulb.create([{ name: "Dude" }, { name: "Bob" }])
assert_equal "Dude", cbs[0].name
assert_equal "Bob", cbs[1].name
assert cbs[0].frickinawesome
assert !cbs[1].frickinawesome
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
@ -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
@ -518,16 +518,16 @@ def test_equality
end
def test_find_by_slug
assert_equal Topic.find('1-meowmeow'), Topic.find(1)
assert_equal Topic.find("1-meowmeow"), Topic.find(1)
end
def test_find_by_slug_with_array
assert_equal Topic.find([1, 2]), Topic.find(['1-meowmeow', '2-hello'])
assert_equal 'The Second Topic of the day', Topic.find(['2-hello', '1-meowmeow']).first.title
assert_equal Topic.find([1, 2]), Topic.find(["1-meowmeow", "2-hello"])
assert_equal "The Second Topic of the day", Topic.find(["2-hello", "1-meowmeow"]).first.title
end
def test_find_by_slug_with_range
assert_equal Topic.where(id: '1-meowmeow'..'2-hello'), Topic.where(id: 1..2)
assert_equal Topic.where(id: "1-meowmeow".."2-hello"), Topic.where(id: 1..2)
end
def test_equality_of_new_records
@ -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
@ -555,8 +555,8 @@ def test_equality_of_relation_and_collection_proxy
car.bulbs.build
car.save
assert car.bulbs == Bulb.where(car_id: car.id), 'CollectionProxy should be comparable with Relation'
assert Bulb.where(car_id: car.id) == car.bulbs, 'Relation should be comparable with CollectionProxy'
assert car.bulbs == Bulb.where(car_id: car.id), "CollectionProxy should be comparable with Relation"
assert Bulb.where(car_id: car.id) == car.bulbs, "Relation should be comparable with CollectionProxy"
end
def test_equality_of_relation_and_array
@ -564,7 +564,7 @@ def test_equality_of_relation_and_array
car.bulbs.build
car.save
assert Bulb.where(car_id: car.id) == car.bulbs.to_a, 'Relation should be comparable with Array'
assert Bulb.where(car_id: car.id) == car.bulbs.to_a, "Relation should be comparable with Array"
end
def test_equality_of_relation_and_association_relation
@ -572,8 +572,8 @@ def test_equality_of_relation_and_association_relation
car.bulbs.build
car.save
assert_equal Bulb.where(car_id: car.id), car.bulbs.includes(:car), 'Relation should be comparable with AssociationRelation'
assert_equal car.bulbs.includes(:car), Bulb.where(car_id: car.id), 'AssociationRelation should be comparable with Relation'
assert_equal Bulb.where(car_id: car.id), car.bulbs.includes(:car), "Relation should be comparable with AssociationRelation"
assert_equal car.bulbs.includes(:car), Bulb.where(car_id: car.id), "AssociationRelation should be comparable with Relation"
end
def test_equality_of_collection_proxy_and_association_relation
@ -581,8 +581,8 @@ def test_equality_of_collection_proxy_and_association_relation
car.bulbs.build
car.save
assert_equal car.bulbs, car.bulbs.includes(:car), 'CollectionProxy should be comparable with AssociationRelation'
assert_equal car.bulbs.includes(:car), car.bulbs, 'AssociationRelation should be comparable with CollectionProxy'
assert_equal car.bulbs, car.bulbs.includes(:car), "CollectionProxy should be comparable with AssociationRelation"
assert_equal car.bulbs.includes(:car), car.bulbs, "AssociationRelation should be comparable with CollectionProxy"
end
def test_hashing
@ -604,14 +604,14 @@ 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)
end
def test_destroy_without_prepared_statement
topic = Topic.create(title: 'foo')
topic = Topic.create(title: "foo")
Topic.connection.unprepared_statement do
Topic.find(topic.id).destroy
end
@ -633,7 +633,7 @@ def test_comparison_with_different_objects_in_array
end
def test_readonly_attributes
assert_equal Set.new([ 'title' , 'comments_count' ]), ReadonlyTitlePost.readonly_attributes
assert_equal Set.new([ "title" , "comments_count" ]), ReadonlyTitlePost.readonly_attributes
post = ReadonlyTitlePost.create(:title => "cannot change this", :body => "changeable")
post.reload
@ -647,8 +647,8 @@ def test_readonly_attributes
def test_unicode_column_name
Weird.reset_column_information
weird = Weird.create(: => 'たこ焼き仮面')
assert_equal 'たこ焼き仮面', weird.
weird = Weird.create(: => "たこ焼き仮面")
assert_equal "たこ焼き仮面", weird.
end
unless current_adapter?(:PostgreSQLAdapter)
@ -666,21 +666,21 @@ def test_respect_internal_encoding
end
def test_non_valid_identifier_column_name
weird = Weird.create('a$b' => 'value')
weird = Weird.create("a$b" => "value")
weird.reload
assert_equal 'value', weird.send('a$b')
assert_equal 'value', weird.read_attribute('a$b')
assert_equal "value", weird.send("a$b")
assert_equal "value", weird.read_attribute("a$b")
weird.update_columns('a$b' => 'value2')
weird.update_columns("a$b" => "value2")
weird.reload
assert_equal 'value2', weird.send('a$b')
assert_equal 'value2', weird.read_attribute('a$b')
assert_equal "value2", weird.send("a$b")
assert_equal "value2", weird.read_attribute("a$b")
end
def test_group_weirds_by_from
Weird.create('a$b' => 'value', :from => 'aaron')
Weird.create("a$b" => "value", :from => "aaron")
count = Weird.group(Weird.arel_table[:from]).count
assert_equal 1, count['aaron']
assert_equal 1, count["aaron"]
end
def test_attributes_on_dummy_time
@ -789,8 +789,8 @@ def test_dup
DeveloperSalary = Struct.new(:amount)
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)]
self.table_name = "developers"
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?
@ -895,15 +895,15 @@ def test_default
assert_equal Time.local(2004, 1,1,0,0,0,0), default.fixed_time
# char types
assert_equal 'Y', default.char1
assert_equal 'a varchar field', default.char2
assert_equal 'a text field', default.char3
assert_equal "Y", default.char1
assert_equal "a varchar field", default.char2
assert_equal "a text field", default.char3
end
end
end
class NumericData < ActiveRecord::Base
self.table_name = 'numeric_data'
self.table_name = "numeric_data"
attribute :my_house_population, :integer
attribute :atoms_in_universe, :integer
@ -1008,7 +1008,7 @@ def test_quoting_arrays
def test_quote
author_name = "\\ \001 ' \n \\n \""
topic = Topic.create('author_name' => author_name)
topic = Topic.create("author_name" => author_name)
assert_equal author_name, Topic.find(topic.id).author_name
end
@ -1087,7 +1087,7 @@ def test_dont_clear_inheritance_column_when_setting_explicitly
def test_set_table_name_symbol_converted_to_string
k = Class.new(Joke)
k.table_name = :cold_jokes
assert_equal 'cold_jokes', k.table_name
assert_equal "cold_jokes", k.table_name
end
def test_quoted_table_name_after_set_table_name
@ -1155,11 +1155,11 @@ def test_no_limit_offset
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,32 +1169,32 @@ 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
@ -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)
@ -1219,7 +1219,7 @@ def test_find_on_abstract_base_class_doesnt_use_type_condition
end
def test_assert_queries
query = lambda { ActiveRecord::Base.connection.execute 'select count(*) from developers' }
query = lambda { ActiveRecord::Base.connection.execute "select count(*) from developers" }
assert_queries(2) { 2.times { query.call } }
assert_queries 1, &query
assert_no_queries { assert true }
@ -1253,9 +1253,9 @@ def test_benchmark_with_use_silence
def test_clear_cache!
# preheat cache
c1 = Post.connection.schema_cache.columns('posts')
c1 = Post.connection.schema_cache.columns("posts")
ActiveRecord::Base.clear_cache!
c2 = Post.connection.schema_cache.columns('posts')
c2 = Post.connection.schema_cache.columns("posts")
c1.each_with_index do |v, i|
assert_not_same v, c2[i]
end
@ -1346,11 +1346,11 @@ def test_attribute_names
end
def test_has_attribute
assert Company.has_attribute?('id')
assert Company.has_attribute?('type')
assert Company.has_attribute?('name')
assert_not Company.has_attribute?('lastname')
assert_not Company.has_attribute?('age')
assert Company.has_attribute?("id")
assert Company.has_attribute?("type")
assert Company.has_attribute?("name")
assert_not Company.has_attribute?("lastname")
assert_not Company.has_attribute?("age")
end
def test_has_attribute_with_symbol
@ -1389,10 +1389,10 @@ def test_table_name_with_2_abstract_subclasses
def test_column_types_typecast
topic = Topic.first
assert_not_equal 't.lo', topic.author_name
assert_not_equal "t.lo", topic.author_name
attrs = topic.attributes.dup
attrs.delete 'id'
attrs.delete "id"
typecast = Class.new(ActiveRecord::Type::Value) {
def cast value
@ -1400,26 +1400,26 @@ def cast value
end
}
types = { 'author_name' => typecast.new }
types = { "author_name" => typecast.new }
topic = Topic.instantiate(attrs, types)
assert_equal 't.lo', topic.author_name
assert_equal "t.lo", topic.author_name
end
def test_typecasting_aliases
assert_equal 10, Topic.select('10 as tenderlove').first.tenderlove
assert_equal 10, Topic.select("10 as tenderlove").first.tenderlove
end
def test_slice
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
assert_equal hash["name"], company.name
assert_equal hash[:rating], company.rating
assert_equal hash['arbitrary_method'], company.arbitrary_method
assert_equal hash["arbitrary_method"], company.arbitrary_method
assert_equal hash[:arbitrary_method], company.arbitrary_method
assert_nil hash[:firm_name]
assert_nil hash['firm_name']
assert_nil hash["firm_name"]
end
def test_default_values_are_deeply_dupped
@ -1430,7 +1430,7 @@ def test_default_values_are_deeply_dupped
test "scoped can take a values hash" do
klass = Class.new(ActiveRecord::Base)
assert_equal ['foo'], klass.all.merge!(select: 'foo').select_values
assert_equal ["foo"], klass.all.merge!(select: "foo").select_values
end
test "connection_handler can be overridden" do
@ -1512,8 +1512,8 @@ def test_default_values_are_deeply_dupped
test "ignored columns are not present in columns_hash" do
cache_columns = Developer.connection.schema_cache.columns_hash(Developer.table_name)
assert_includes cache_columns.keys, 'first_name'
refute_includes Developer.columns_hash.keys, 'first_name'
assert_includes cache_columns.keys, "first_name"
refute_includes Developer.columns_hash.keys, "first_name"
end
test "ignored columns have no attribute methods" do

@ -1,6 +1,6 @@
require 'cases/helper'
require 'models/post'
require 'models/subscriber'
require "cases/helper"
require "models/post"
require "models/subscriber"
class EachTest < ActiveRecord::TestCase
fixtures :posts, :subscribers
@ -8,7 +8,7 @@ class EachTest < ActiveRecord::TestCase
def setup
@posts = Post.order("id asc")
@total = Post.count
Post.count('id') # preheat arel's table cache
Post.count("id") # preheat arel's table cache
end
def test_each_should_execute_one_query_per_batch
@ -68,7 +68,7 @@ def test_each_should_execute_if_id_is_in_select
end
end
test 'find_each should honor limit if passed a block' do
test "find_each should honor limit if passed a block" do
limit = @total - 1
total = 0
@ -79,7 +79,7 @@ def test_each_should_execute_if_id_is_in_select
assert_equal limit, total
end
test 'find_each should honor limit if no block is passed' do
test "find_each should honor limit if no block is passed" do
limit = @total - 1
total = 0
@ -100,7 +100,7 @@ def test_logger_not_required
previous_logger = ActiveRecord::Base.logger
ActiveRecord::Base.logger = nil
assert_nothing_raised do
Post.order('comments_count DESC').find_each { |post| post }
Post.order("comments_count DESC").find_each { |post| post }
end
ensure
ActiveRecord::Base.logger = previous_logger
@ -232,7 +232,7 @@ def test_find_in_batches_should_not_modify_passed_options
end
def test_find_in_batches_should_use_any_column_as_primary_key
nick_order_subscribers = Subscriber.order('nick asc')
nick_order_subscribers = Subscriber.order("nick asc")
start_nick = nick_order_subscribers.second.nick
subscribers = []
@ -265,7 +265,7 @@ def test_find_in_batches_should_return_an_enumerator
end
end
test 'find_in_batches should honor limit if passed a block' do
test "find_in_batches should honor limit if passed a block" do
limit = @total - 1
total = 0
@ -276,7 +276,7 @@ def test_find_in_batches_should_return_an_enumerator
assert_equal limit, total
end
test 'find_in_batches should honor limit if no block is passed' do
test "find_in_batches should honor limit if no block is passed" do
limit = @total - 1
total = 0
@ -328,7 +328,7 @@ def test_in_batches_each_record_should_return_enumerator_if_no_block_given
end
def test_in_batches_each_record_should_be_ordered_by_id
ids = Post.order('id ASC').pluck(:id)
ids = Post.order("id ASC").pluck(:id)
assert_queries(6) do
Post.in_batches(of: 2).each_record.with_index do |post, i|
assert_equal ids[i], post.id
@ -344,9 +344,9 @@ def test_in_batches_update_all_affect_all_records
end
def test_in_batches_delete_all_should_not_delete_records_in_other_batches
not_deleted_count = Post.where('id <= 2').count
Post.where('id > 2').in_batches(of: 2).delete_all
assert_equal 0, Post.where('id > 2').count
not_deleted_count = Post.where("id <= 2").count
Post.where("id > 2").in_batches(of: 2).delete_all
assert_equal 0, Post.where("id > 2").count
assert_equal not_deleted_count, Post.count
end
@ -383,7 +383,7 @@ def test_in_batches_should_return_relations
end
def test_in_batches_should_start_from_the_start_option
post = Post.order('id ASC').where('id >= ?', 2).first
post = Post.order("id ASC").where("id >= ?", 2).first
assert_queries(2) do
relation = Post.in_batches(of: 1, start: 2).first
assert_equal post, relation.first
@ -391,7 +391,7 @@ def test_in_batches_should_start_from_the_start_option
end
def test_in_batches_should_end_at_the_finish_option
post = Post.order('id DESC').where('id <= ?', 5).first
post = Post.order("id DESC").where("id <= ?", 5).first
assert_queries(7) do
relation = Post.in_batches(of: 1, finish: 5, load: true).reverse_each.first
assert_equal post, relation.last
@ -450,7 +450,7 @@ def test_in_batches_should_not_modify_passed_options
end
def test_in_batches_should_use_any_column_as_primary_key
nick_order_subscribers = Subscriber.order('nick asc')
nick_order_subscribers = Subscriber.order("nick asc")
start_nick = nick_order_subscribers.second.nick
subscribers = []
@ -510,7 +510,7 @@ def test_in_batches_relations_update_all_should_not_affect_matching_records_in_o
person.update_attributes(author_id: 1)
Post.in_batches(of: 2) do |batch|
batch.where('author_id >= 1').update_all('author_id = author_id + 1')
batch.where("author_id >= 1").update_all("author_id = author_id + 1")
end
assert_equal 2, person.reload.author_id # incremented only once
end
@ -587,10 +587,10 @@ def test_find_in_batches_should_return_a_sized_enumerator
end
end
test '.error_on_ignored_order_or_limit= is deprecated' do
test ".error_on_ignored_order_or_limit= is deprecated" do
begin
prev = ActiveRecord::Base.error_on_ignored_order
assert_deprecated 'Please use error_on_ignored_order= instead.' do
assert_deprecated "Please use error_on_ignored_order= instead." do
ActiveRecord::Base.error_on_ignored_order_or_limit = true
end
assert ActiveRecord::Base.error_on_ignored_order
@ -599,17 +599,17 @@ def test_find_in_batches_should_return_a_sized_enumerator
end
end
test '.error_on_ignored_order_or_limit is deprecated' do
test ".error_on_ignored_order_or_limit is deprecated" do
expected = ActiveRecord::Base.error_on_ignored_order
actual = assert_deprecated 'Please use error_on_ignored_order instead.' do
actual = assert_deprecated "Please use error_on_ignored_order instead." do
ActiveRecord::Base.error_on_ignored_order_or_limit
end
assert_equal expected, actual
end
test '#error_on_ignored_order_or_limit is deprecated' do
test "#error_on_ignored_order_or_limit is deprecated" do
expected = ActiveRecord::Base.error_on_ignored_order
actual = assert_deprecated 'Please use error_on_ignored_order instead.' do
actual = assert_deprecated "Please use error_on_ignored_order instead." do
Post.new.error_on_ignored_order_or_limit
end
assert_equal expected, actual

@ -4,23 +4,23 @@
# BLOB data with DB2, because the length of a statement
# is limited to 32KB.
unless current_adapter?(:DB2Adapter)
require 'models/binary'
require "models/binary"
class BinaryTest < ActiveRecord::TestCase
FIXTURES = %w(flowers.jpg example.log test.txt)
def test_mixed_encoding
str = "\x80"
str.force_encoding('ASCII-8BIT')
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
name = binary.name
assert_equal 'いただきます!', name
assert_equal "いただきます!", name
end
def test_load_save
@ -28,16 +28,16 @@ def test_load_save
FIXTURES.each do |filename|
data = File.read(ASSETS_ROOT + "/#{filename}")
data.force_encoding('ASCII-8BIT')
data.force_encoding("ASCII-8BIT")
data.freeze
bin = Binary.new(:data => data)
assert_equal data, bin.data, 'Newly assigned data differs from original'
assert_equal data, bin.data, "Newly assigned data differs from original"
bin.save!
assert_equal data, bin.data, 'Data differs from original after save'
assert_equal data, bin.data, "Data differs from original after save"
assert_equal data, bin.reload.data, 'Reloaded data differs from original'
assert_equal data, bin.reload.data, "Reloaded data differs from original"
end
end
end

@ -1,7 +1,7 @@
require 'cases/helper'
require 'models/topic'
require 'models/author'
require 'models/post'
require "cases/helper"
require "models/topic"
require "models/author"
require "models/post"
module ActiveRecord
class BindParameterTest < ActiveRecord::TestCase
@ -24,7 +24,7 @@ def setup
@connection = ActiveRecord::Base.connection
@subscriber = LogListener.new
@pk = Topic.columns_hash[Topic.primary_key]
@subscription = ActiveSupport::Notifications.subscribe('sql.active_record', @subscriber)
@subscription = ActiveSupport::Notifications.subscribe("sql.active_record", @subscriber)
end
teardown do
@ -34,8 +34,8 @@ def setup
if ActiveRecord::Base.connection.supports_statement_cache? &&
ActiveRecord::Base.connection.prepared_statements
def test_bind_from_join_in_subquery
subquery = Author.joins(:thinking_posts).where(name: 'David')
scope = Author.from(subquery, 'authors').where(id: 1)
subquery = Author.joins(:thinking_posts).where(name: "David")
scope = Author.from(subquery, "authors").where(id: 1)
assert_equal 1, scope.count
end
@ -44,7 +44,7 @@ def test_binds_are_logged
binds = [Relation::QueryAttribute.new("id", 1, Type::Value.new)]
sql = "select * from topics where id = #{sub.to_sql}"
@connection.exec_query(sql, 'SQL', binds)
@connection.exec_query(sql, "SQL", binds)
message = @subscriber.calls.find { |args| args[4][:sql] == sql }
assert_equal binds, message[4][:binds]
@ -53,20 +53,20 @@ def test_binds_are_logged
def test_find_one_uses_binds
Topic.find(1)
message = @subscriber.calls.find { |args| args[4][:binds].any? { |attr| attr.value == 1 } }
assert message, 'expected a message with binds'
assert message, "expected a message with binds"
end
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 = ?',
:name => "SQL",
:sql => "select * from topics where id = ?",
:binds => binds,
:type_casted_binds => type_casted_binds
}
event = ActiveSupport::Notifications::Event.new(
'foo',
"foo",
Time.now,
Time.now,
123,

@ -1,24 +1,24 @@
require "cases/helper"
require "models/book"
require 'models/club'
require 'models/company'
require "models/club"
require "models/company"
require "models/contract"
require 'models/edge'
require 'models/organization'
require 'models/possession'
require 'models/topic'
require 'models/reply'
require 'models/minivan'
require 'models/speedometer'
require 'models/ship_part'
require 'models/treasure'
require 'models/developer'
require 'models/comment'
require 'models/rating'
require 'models/post'
require "models/edge"
require "models/organization"
require "models/possession"
require "models/topic"
require "models/reply"
require "models/minivan"
require "models/speedometer"
require "models/ship_part"
require "models/treasure"
require "models/developer"
require "models/comment"
require "models/rating"
require "models/post"
class NumericData < ActiveRecord::Base
self.table_name = 'numeric_data'
self.table_name = "numeric_data"
attribute :world_population, :integer
attribute :my_house_population, :integer
@ -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
@ -105,12 +105,12 @@ def test_should_group_by_arel_attribute
end
def test_should_group_by_multiple_fields
c = Account.group('firm_id', :credit_limit).count(:all)
c = Account.group("firm_id", :credit_limit).count(:all)
[ [nil, 50], [1, 50], [6, 50], [6, 55], [9, 53], [2, 60] ].each { |firm_and_limit| assert c.keys.include?(firm_and_limit) }
end
def test_should_group_by_multiple_fields_having_functions
c = Topic.group(:author_name, 'COALESCE(type, title)').count(:all)
c = Topic.group(:author_name, "COALESCE(type, title)").count(:all)
assert_equal 1, c[["Carl", "The Third Topic of the day"]]
assert_equal 1, c[["Mary", "Reply"]]
assert_equal 1, c[["David", "The First Topic"]]
@ -166,14 +166,14 @@ def test_should_limit_calculation_with_offset
end
def test_limit_should_apply_before_count
accounts = Account.limit(3).where('firm_id IS NOT NULL')
accounts = Account.limit(3).where("firm_id IS NOT NULL")
assert_equal 3, accounts.count(:firm_id)
assert_equal 3, accounts.select(:firm_id).count
end
def test_limit_should_apply_before_count_arel_attribute
accounts = Account.limit(3).where('firm_id IS NOT NULL')
accounts = Account.limit(3).where("firm_id IS NOT NULL")
firm_id_attribute = Account.arel_table[:firm_id]
assert_equal 3, accounts.count(firm_id_attribute)
@ -228,7 +228,7 @@ def test_count_on_invalid_columns_raises
end
def test_should_group_by_summed_field_having_condition
c = Account.group(:firm_id).having('sum(credit_limit) > 50').sum(:credit_limit)
c = Account.group(:firm_id).having("sum(credit_limit) > 50").sum(:credit_limit)
assert_nil c[1]
assert_equal 105, c[6]
assert_equal 60, c[2]
@ -249,12 +249,12 @@ def test_should_group_by_summed_association
end
def test_should_sum_field_with_conditions
assert_equal 105, Account.where('firm_id = 6').sum(:credit_limit)
assert_equal 105, Account.where("firm_id = 6").sum(:credit_limit)
end
def test_should_return_zero_if_sum_conditions_return_nothing
assert_equal 0, Account.where('1 = 2').sum(:credit_limit)
assert_equal 0, companies(:rails_core).companies.where('1 = 2').sum(:id)
assert_equal 0, Account.where("1 = 2").sum(:credit_limit)
assert_equal 0, companies(:rails_core).companies.where("1 = 2").sum(:id)
end
def test_sum_should_return_valid_values_for_decimals
@ -263,38 +263,38 @@ def test_sum_should_return_valid_values_for_decimals
end
def test_should_return_type_casted_values_with_group_and_expression
assert_equal 0.5, Account.group(:firm_name).sum('0.01 * credit_limit')['37signals']
assert_equal 0.5, Account.group(:firm_name).sum("0.01 * credit_limit")["37signals"]
end
def test_should_group_by_summed_field_with_conditions
c = Account.where('firm_id > 1').group(:firm_id).sum(:credit_limit)
c = Account.where("firm_id > 1").group(:firm_id).sum(:credit_limit)
assert_nil c[1]
assert_equal 105, c[6]
assert_equal 60, c[2]
end
def test_should_group_by_summed_field_with_conditions_and_having
c = Account.where('firm_id > 1').group(:firm_id).
having('sum(credit_limit) > 60').sum(:credit_limit)
c = Account.where("firm_id > 1").group(:firm_id).
having("sum(credit_limit) > 60").sum(:credit_limit)
assert_nil c[1]
assert_equal 105, c[6]
assert_nil c[2]
end
def test_should_group_by_fields_with_table_alias
c = Account.group('accounts.firm_id').sum(:credit_limit)
c = Account.group("accounts.firm_id").sum(:credit_limit)
assert_equal 50, c[1]
assert_equal 105, c[6]
assert_equal 60, c[2]
end
def test_should_calculate_with_invalid_field
assert_equal 6, Account.calculate(:count, '*')
assert_equal 6, Account.calculate(:count, "*")
assert_equal 6, Account.calculate(:count, :all)
end
def test_should_calculate_grouped_with_invalid_field
c = Account.group('accounts.firm_id').count(:all)
c = Account.group("accounts.firm_id").count(:all)
assert_equal 1, c[1]
assert_equal 2, c[6]
assert_equal 1, c[2]
@ -308,8 +308,8 @@ def test_should_calculate_grouped_association_with_invalid_field
end
def test_should_group_by_association_with_non_numeric_foreign_key
Speedometer.create! id: 'ABC'
Minivan.create! id: 'OMG', speedometer_id: 'ABC'
Speedometer.create! id: "ABC"
Minivan.create! id: "OMG", speedometer_id: "ABC"
c = Minivan.group(:speedometer).count(:all)
first_key = c.keys.first
@ -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)]
@ -328,17 +328,17 @@ def test_should_calculate_grouped_association_with_foreign_key_option
def test_should_calculate_grouped_by_function
c = Company.group("UPPER(#{QUOTED_TYPE})").count(:all)
assert_equal 2, c[nil]
assert_equal 1, c['DEPENDENTFIRM']
assert_equal 5, c['CLIENT']
assert_equal 2, c['FIRM']
assert_equal 1, c["DEPENDENTFIRM"]
assert_equal 5, c["CLIENT"]
assert_equal 2, c["FIRM"]
end
def test_should_calculate_grouped_by_function_with_table_alias
c = Company.group("UPPER(companies.#{QUOTED_TYPE})").count(:all)
assert_equal 2, c[nil]
assert_equal 1, c['DEPENDENTFIRM']
assert_equal 5, c['CLIENT']
assert_equal 2, c['FIRM']
assert_equal 1, c["DEPENDENTFIRM"]
assert_equal 5, c["CLIENT"]
assert_equal 2, c["FIRM"]
end
def test_should_not_overshadow_enumerable_sum
@ -354,19 +354,19 @@ def test_should_sum_scoped_field_with_from
end
def test_should_sum_scoped_field_with_conditions
assert_equal 8, companies(:rails_core).companies.where('id > 7').sum(:id)
assert_equal 8, companies(:rails_core).companies.where("id > 7").sum(:id)
end
def test_should_group_by_scoped_field
c = companies(:rails_core).companies.group(:name).sum(:id)
assert_equal 7, c['Leetsoft']
assert_equal 8, c['Jadedpixel']
assert_equal 7, c["Leetsoft"]
assert_equal 8, c["Jadedpixel"]
end
def test_should_group_by_summed_field_through_association_and_having
c = companies(:rails_core).companies.group(:name).having('sum(id) > 7').sum(:id)
assert_nil c['Leetsoft']
assert_equal 8, c['Jadedpixel']
c = companies(:rails_core).companies.group(:name).having("sum(id) > 7").sum(:id)
assert_nil c["Leetsoft"]
assert_equal 8, c["Jadedpixel"]
end
def test_should_count_selected_field_with_include
@ -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
@ -392,10 +392,10 @@ def test_should_count_scoped_select
def test_should_count_scoped_select_with_options
Account.update_all("credit_limit = NULL")
Account.last.update_columns('credit_limit' => 49)
Account.first.update_columns('credit_limit' => 51)
Account.last.update_columns("credit_limit" => 49)
Account.first.update_columns("credit_limit" => 51)
assert_equal 1, Account.select("credit_limit").where('credit_limit >= 50').count
assert_equal 1, Account.select("credit_limit").where("credit_limit >= 50").count
end
def test_should_count_manual_select_with_include
@ -436,8 +436,8 @@ def test_count_with_column_and_options_parameter
end
def test_should_count_field_in_joined_table
assert_equal 5, Account.joins(:firm).count('companies.id')
assert_equal 4, Account.joins(:firm).distinct.count('companies.id')
assert_equal 5, Account.joins(:firm).count("companies.id")
assert_equal 4, Account.joins(:firm).distinct.count("companies.id")
end
def test_count_arel_attribute_in_joined_table_with
@ -451,14 +451,14 @@ def test_count_selected_arel_attribute_in_joined_table
end
def test_should_count_field_in_joined_table_with_group_by
c = Account.group('accounts.firm_id').joins(:firm).count('companies.id')
c = Account.group("accounts.firm_id").joins(:firm).count("companies.id")
[1,6,2,9].each { |firm_id| assert c.keys.include?(firm_id) }
end
def test_should_count_field_of_root_table_with_conflicting_group_by_column
assert_equal({ 1 => 1 }, Firm.joins(:accounts).group(:firm_id).count)
assert_equal({ 1 => 1 }, Firm.joins(:accounts).group('accounts.firm_id').count)
assert_equal({ 1 => 1 }, Firm.joins(:accounts).group("accounts.firm_id").count)
end
def test_count_with_no_parameters_isnt_deprecated
@ -478,9 +478,9 @@ def test_count_with_reverse_order
end
def test_count_with_where_and_order
assert_equal 1, Account.where(firm_name: '37signals').count
assert_equal 1, Account.where(firm_name: '37signals').order(:firm_name).count
assert_equal 1, Account.where(firm_name: '37signals').order(:firm_name).reverse_order.count
assert_equal 1, Account.where(firm_name: "37signals").count
assert_equal 1, Account.where(firm_name: "37signals").order(:firm_name).count
assert_equal 1, Account.where(firm_name: "37signals").order(:firm_name).reverse_order.count
end
def test_count_with_block
@ -497,39 +497,39 @@ def test_should_sum_expression
end
def test_sum_expression_returns_zero_when_no_records_to_sum
assert_equal 0, Account.where('1 = 2').sum("2 * credit_limit")
assert_equal 0, Account.where("1 = 2").sum("2 * credit_limit")
end
def test_count_with_from_option
assert_equal Company.count(:all), Company.from('companies').count(:all)
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)
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)
Company.where(:type => "Firm").from("companies").count(:type)
end
def test_sum_with_from_option
assert_equal Account.sum(:credit_limit), Account.from('accounts').sum(:credit_limit)
assert_equal Account.sum(:credit_limit), Account.from("accounts").sum(:credit_limit)
assert_equal Account.where("credit_limit > 50").sum(:credit_limit),
Account.where("credit_limit > 50").from('accounts').sum(:credit_limit)
Account.where("credit_limit > 50").from("accounts").sum(:credit_limit)
end
def test_average_with_from_option
assert_equal Account.average(:credit_limit), Account.from('accounts').average(:credit_limit)
assert_equal Account.average(:credit_limit), Account.from("accounts").average(:credit_limit)
assert_equal Account.where("credit_limit > 50").average(:credit_limit),
Account.where("credit_limit > 50").from('accounts').average(:credit_limit)
Account.where("credit_limit > 50").from("accounts").average(:credit_limit)
end
def test_minimum_with_from_option
assert_equal Account.minimum(:credit_limit), Account.from('accounts').minimum(:credit_limit)
assert_equal Account.minimum(:credit_limit), Account.from("accounts").minimum(:credit_limit)
assert_equal Account.where("credit_limit > 50").minimum(:credit_limit),
Account.where("credit_limit > 50").from('accounts').minimum(:credit_limit)
Account.where("credit_limit > 50").from("accounts").minimum(:credit_limit)
end
def test_maximum_with_from_option
assert_equal Account.maximum(:credit_limit), Account.from('accounts').maximum(:credit_limit)
assert_equal Account.maximum(:credit_limit), Account.from("accounts").maximum(:credit_limit)
assert_equal Account.where("credit_limit > 50").maximum(:credit_limit),
Account.where("credit_limit > 50").from('accounts').maximum(:credit_limit)
Account.where("credit_limit > 50").from("accounts").maximum(:credit_limit)
end
def test_maximum_with_not_auto_table_name_prefix_if_column_included
@ -552,14 +552,14 @@ def test_sum_with_not_auto_table_name_prefix_if_column_included
if current_adapter?(:Mysql2Adapter)
def test_from_option_with_specified_index
assert_equal Edge.count(:all), Edge.from('edges USE INDEX(unique_edge_index)').count(:all)
assert_equal Edge.where('sink_id < 5').count(:all),
Edge.from('edges USE INDEX(unique_edge_index)').where('sink_id < 5').count(:all)
assert_equal Edge.count(:all), Edge.from("edges USE INDEX(unique_edge_index)").count(:all)
assert_equal Edge.where("sink_id < 5").count(:all),
Edge.from("edges USE INDEX(unique_edge_index)").where("sink_id < 5").count(:all)
end
end
def test_from_option_with_table_different_than_class
assert_equal Account.count(:all), Company.from('accounts').count(:all)
assert_equal Account.count(:all), Company.from("accounts").count(:all)
end
def test_distinct_is_honored_when_used_with_count_operation_after_group
@ -599,7 +599,7 @@ def test_pluck_in_relation
end
def test_pluck_on_aliased_attribute
assert_equal 'The First Topic', Topic.order(:id).pluck(:heading).first
assert_equal "The First Topic", Topic.order(:id).pluck(:heading).first
end
def test_pluck_with_serialization
@ -627,14 +627,14 @@ def test_pluck_not_auto_table_name_prefix_if_column_joined
end
def test_pluck_with_selection_clause
assert_equal [50, 53, 55, 60], Account.pluck('DISTINCT credit_limit').sort
assert_equal [50, 53, 55, 60], Account.pluck('DISTINCT accounts.credit_limit').sort
assert_equal [50, 53, 55, 60], Account.pluck('DISTINCT(credit_limit)').sort
assert_equal [50, 53, 55, 60], Account.pluck("DISTINCT credit_limit").sort
assert_equal [50, 53, 55, 60], Account.pluck("DISTINCT accounts.credit_limit").sort
assert_equal [50, 53, 55, 60], Account.pluck("DISTINCT(credit_limit)").sort
# MySQL returns "SUM(DISTINCT(credit_limit))" as the column name unless
# an alias is provided. Without the alias, the column cannot be found
# and properly typecast.
assert_equal [50 + 53 + 55 + 60], Account.pluck('SUM(DISTINCT(credit_limit)) as credit_limit')
assert_equal [50 + 53 + 55 + 60], Account.pluck("SUM(DISTINCT(credit_limit)) as credit_limit")
end
def test_plucks_with_ids
@ -643,7 +643,7 @@ def test_plucks_with_ids
def test_pluck_with_includes_limit_and_empty_result
assert_equal [], Topic.includes(:replies).limit(0).pluck(:id)
assert_equal [], Topic.includes(:replies).limit(1).where('0 = 1').pluck(:id)
assert_equal [], Topic.includes(:replies).limit(1).where("0 = 1").pluck(:id)
end
def test_pluck_not_auto_table_name_prefix_if_column_included
@ -668,12 +668,12 @@ def test_pluck_multiple_columns
def test_pluck_with_multiple_columns_and_selection_clause
assert_equal [[1, 50], [2, 50], [3, 50], [4, 60], [5, 55], [6, 53]],
Account.pluck('id, credit_limit')
Account.pluck("id, credit_limit")
end
def test_pluck_with_multiple_columns_and_includes
Company.create!(:name => "test", :contracts => [Contract.new(:developer_id => 7)])
companies_and_developers = Company.order('companies.id').includes(:contracts).pluck(:name, :developer_id)
companies_and_developers = Company.order("companies.id").includes(:contracts).pluck(:name, :developer_id)
assert_equal Company.count, companies_and_developers.length
assert_equal ["37signals", nil], companies_and_developers.first
@ -695,7 +695,7 @@ def test_pluck_replaces_select_clause
def test_pluck_columns_with_same_name
expected = [["The First Topic", "The Second Topic of the day"], ["The Third Topic of the day", "The Fourth Topic of the day"]]
actual = Topic.joins(:replies)
.pluck('topics.title', 'replies_topics.title')
.pluck("topics.title", "replies_topics.title")
assert_equal expected, actual
end
@ -716,21 +716,21 @@ def test_pluck_joined_with_polymorphic_relation
def test_pluck_loaded_relation
companies = Company.order(:id).limit(3).load
assert_no_queries do
assert_equal ['37signals', 'Summit', 'Microsoft'], companies.pluck(:name)
assert_equal ["37signals", "Summit", "Microsoft"], companies.pluck(:name)
end
end
def test_pluck_loaded_relation_multiple_columns
companies = Company.order(:id).limit(3).load
assert_no_queries do
assert_equal [[1, '37signals'], [2, 'Summit'], [3, 'Microsoft']], companies.pluck(:id, :name)
assert_equal [[1, "37signals"], [2, "Summit"], [3, "Microsoft"]], companies.pluck(:id, :name)
end
end
def test_pluck_loaded_relation_sql_fragment
companies = Company.order(:name).limit(3).load
assert_queries 1 do
assert_equal ['37signals', 'Apex', 'Ex Nihilo'], companies.pluck('DISTINCT name')
assert_equal ["37signals", "Apex", "Ex Nihilo"], companies.pluck("DISTINCT name")
end
end
@ -748,7 +748,7 @@ def test_calculation_grouped_by_association_doesnt_error_when_no_records_have_as
def test_should_reference_correct_aliases_while_joining_tables_of_has_many_through_association
assert_nothing_raised do
developer = Developer.create!(name: 'developer')
developer = Developer.create!(name: "developer")
developer.ratings.includes(comment: :post).where(posts: { id: 1 }).count
end
end
@ -783,7 +783,7 @@ def permit!
end
end
params = protected_params.new(credit_limit: '50')
params = protected_params.new(credit_limit: "50")
assert_raises(ActiveModel::ForbiddenAttributesError) do
Account.group(:id).having(params)

@ -1,9 +1,9 @@
require "cases/helper"
require 'models/developer'
require 'models/computer'
require "models/developer"
require "models/computer"
class CallbackDeveloper < ActiveRecord::Base
self.table_name = 'developers'
self.table_name = "developers"
class << self
def callback_string(callback_method)
@ -31,7 +31,7 @@ def callback_object(callback_method)
end
ActiveRecord::Callbacks::CALLBACKS.each do |callback_method|
next if callback_method.to_s.start_with?('around_')
next if callback_method.to_s.start_with?("around_")
define_callback_method(callback_method)
ActiveSupport::Deprecation.silence { send(callback_method, callback_string(callback_method)) }
send(callback_method, callback_proc(callback_method))
@ -55,7 +55,7 @@ class CallbackDeveloperWithHaltedValidation < CallbackDeveloper
end
class ParentDeveloper < ActiveRecord::Base
self.table_name = 'developers'
self.table_name = "developers"
attr_accessor :after_save_called
before_validation {|record| record.after_save_called = true}
end
@ -65,7 +65,7 @@ class ChildDeveloper < ParentDeveloper
end
class ImmutableDeveloper < ActiveRecord::Base
self.table_name = 'developers'
self.table_name = "developers"
validates_inclusion_of :salary, :in => 50000..200000
@ -79,7 +79,7 @@ def cancel
end
class DeveloperWithCanceledCallbacks < ActiveRecord::Base
self.table_name = 'developers'
self.table_name = "developers"
validates_inclusion_of :salary, in: 50000..200000
@ -93,7 +93,7 @@ def cancel
end
class OnCallbacksDeveloper < ActiveRecord::Base
self.table_name = 'developers'
self.table_name = "developers"
before_validation { history << :before_validation }
before_validation(:on => :create){ history << :before_validation_on_create }
@ -113,7 +113,7 @@ def history
end
class ContextualCallbacksDeveloper < ActiveRecord::Base
self.table_name = 'developers'
self.table_name = "developers"
before_validation { history << :before_validation }
before_validation :before_validation_on_create_and_update, :on => [ :create, :update ]
@ -139,7 +139,7 @@ def history
end
class CallbackCancellationDeveloper < ActiveRecord::Base
self.table_name = 'developers'
self.table_name = "developers"
attr_reader :after_save_called, :after_create_called, :after_update_called, :after_destroy_called
attr_accessor :cancel_before_save, :cancel_before_create, :cancel_before_update, :cancel_before_destroy
@ -156,7 +156,7 @@ class CallbackCancellationDeveloper < ActiveRecord::Base
end
class CallbackHaltedDeveloper < ActiveRecord::Base
self.table_name = 'developers'
self.table_name = "developers"
attr_reader :after_save_called, :after_create_called, :after_update_called, :after_destroy_called
attr_accessor :cancel_before_save, :cancel_before_create, :cancel_before_update, :cancel_before_destroy
@ -252,7 +252,7 @@ def test_existing_valid?
end
def test_create
david = CallbackDeveloper.create('name' => 'David', 'salary' => 1000000)
david = CallbackDeveloper.create("name" => "David", "salary" => 1000000)
assert_equal [
[ :after_initialize, :method ],
[ :after_initialize, :string ],
@ -298,7 +298,7 @@ def test_create
end
def test_validate_on_create
david = OnCallbacksDeveloper.create('name' => 'David', 'salary' => 1000000)
david = OnCallbacksDeveloper.create("name" => "David", "salary" => 1000000)
assert_equal [
:before_validation,
:before_validation_on_create,
@ -309,7 +309,7 @@ def test_validate_on_create
end
def test_validate_on_contextual_create
david = ContextualCallbacksDeveloper.create('name' => 'David', 'salary' => 1000000)
david = ContextualCallbacksDeveloper.create("name" => "David", "salary" => 1000000)
assert_equal [
:before_validation,
:before_validation_on_create,

@ -1,5 +1,5 @@
require "cases/helper"
require 'models/topic'
require "models/topic"
module ActiveRecord
class CloneTest < ActiveRecord::TestCase
@ -8,9 +8,9 @@ class CloneTest < ActiveRecord::TestCase
def test_persisted
topic = Topic.first
cloned = topic.clone
assert topic.persisted?, 'topic persisted'
assert cloned.persisted?, 'topic persisted'
assert !cloned.new_record?, 'topic is not new'
assert topic.persisted?, "topic persisted"
assert cloned.persisted?, "topic persisted"
assert !cloned.new_record?, "topic is not new"
end
def test_stays_frozen
@ -18,16 +18,16 @@ def test_stays_frozen
topic.freeze
cloned = topic.clone
assert cloned.persisted?, 'topic persisted'
assert !cloned.new_record?, 'topic is not new'
assert cloned.frozen?, 'topic should be frozen'
assert cloned.persisted?, "topic persisted"
assert !cloned.new_record?, "topic is not new"
assert cloned.frozen?, "topic should be frozen"
end
def test_shallow
topic = Topic.first
cloned = topic.clone
topic.author_name = 'Aaron'
assert_equal 'Aaron', cloned.author_name
topic.author_name = "Aaron"
assert_equal "Aaron", cloned.author_name
end
def test_freezing_a_cloned_model_does_not_freeze_clone

@ -35,7 +35,7 @@ def test_returns_new_with_different_class
def test_returns_string_unless_starts_with_dash
coder = YAMLColumn.new
assert_equal 'foo', coder.load("foo")
assert_equal "foo", coder.load("foo")
end
def test_load_handles_other_classes
@ -45,7 +45,7 @@ def test_load_handles_other_classes
def test_load_doesnt_swallow_yaml_exceptions
coder = YAMLColumn.new
bad_yaml = '--- {'
bad_yaml = "--- {"
assert_raises(Psych::SyntaxError) do
coder.load(bad_yaml)
end

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