1 require 'abstract_unit'
2 require 'fixtures/topic'
3 require 'fixtures/reply'
4 require 'fixtures/company'
5 require 'fixtures/customer'
6 require 'fixtures/developer'
7 require 'fixtures/project'
8 require 'fixtures/default'
9 require 'fixtures/auto_id'
10 require 'fixtures/column_name'
11 require 'fixtures/subscriber'
12 require 'fixtures/keyboard'
13 require 'fixtures/post'
14 require 'fixtures/minimalistic'
15 require 'rexml/document'
17 class Category < ActiveRecord::Base; end
18 class Smarts < ActiveRecord::Base; end
19 class CreditCard < ActiveRecord::Base
20 class PinNumber < ActiveRecord::Base
21 class CvvCode < ActiveRecord::Base; end
22 class SubCvvCode < CvvCode; end
24 class SubPinNumber < PinNumber; end
25 class Brand < Category; end
27 class MasterCreditCard < ActiveRecord::Base; end
28 class Post < ActiveRecord::Base; end
29 class Computer < ActiveRecord::Base; end
30 class NonExistentTable < ActiveRecord::Base; end
31 class TestOracleDefault < ActiveRecord::Base; end
33 class LoosePerson < ActiveRecord::Base
34 self.table_name = 'people'
35 self.abstract_class = true
36 attr_protected :credit_rating, :administrator
39 class LooseDescendant < LoosePerson
40 attr_protected :phone_number
43 class TightPerson < ActiveRecord::Base
44 self.table_name = 'people'
45 attr_accessible :name, :address
48 class TightDescendant < TightPerson
49 attr_accessible :phone_number
52 class ReadonlyTitlePost < Post
56 class Booleantest < ActiveRecord::Base; end
58 class Task < ActiveRecord::Base
59 attr_protected :starting
62 class TopicWithProtectedContentAndAccessibleAuthorName < ActiveRecord::Base
63 self.table_name = 'topics'
64 attr_accessible :author_name
65 attr_protected :content
68 class BasicsTest < Test::Unit::TestCase
69 fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics
72 assert !NonExistentTable.table_exists?
73 assert Topic.table_exists?
76 def test_set_attributes
78 topic.attributes = { "title" => "Budget", "author_name" => "Jason" }
80 assert_equal("Budget", topic.title)
81 assert_equal("Jason", topic.author_name)
82 assert_equal(topics(:first).author_email_address, Topic.find(1).author_email_address)
85 def test_integers_as_nil
86 test = AutoId.create('value' => '')
87 assert_nil AutoId.find(test.id).value
90 def test_set_attributes_with_block
91 topic = Topic.new do |t|
93 t.author_name = "Jason"
96 assert_equal("Budget", topic.title)
97 assert_equal("Jason", topic.author_name)
101 topic = Topic.find(1)
102 assert topic.respond_to?("title")
103 assert topic.respond_to?("title?")
104 assert topic.respond_to?("title=")
105 assert topic.respond_to?(:title)
106 assert topic.respond_to?(:title?)
107 assert topic.respond_to?(:title=)
108 assert topic.respond_to?("author_name")
109 assert topic.respond_to?("attribute_names")
110 assert !topic.respond_to?("nothingness")
111 assert !topic.respond_to?(:nothingness)
114 def test_array_content
116 topic.content = %w( one two three )
119 assert_equal(%w( one two three ), Topic.find(topic.id).content)
122 def test_hash_content
124 topic.content = { "one" => 1, "two" => 2 }
127 assert_equal 2, Topic.find(topic.id).content["two"]
129 topic.content["three"] = 3
132 assert_equal 3, Topic.find(topic.id).content["three"]
135 def test_update_array_content
137 topic.content = %w( one two three )
139 topic.content.push "four"
140 assert_equal(%w( one two three four ), topic.content)
144 topic = Topic.find(topic.id)
145 topic.content << "five"
146 assert_equal(%w( one two three four five ), topic.content)
149 def test_case_sensitive_attributes_hash
150 # DB2 is not case-sensitive
151 return true if current_adapter?(:DB2Adapter)
153 assert_equal @loaded_fixtures['computers']['workstation'].to_hash, Computer.find(:first).attributes
158 topic.title = "New Topic"
160 topic_reloaded = Topic.find(topic.id)
161 assert_equal("New Topic", topic_reloaded.title)
165 topic = Topic.new(:title => "New Topic")
169 assert_raise(ActiveRecord::RecordInvalid) { reply.save! }
172 def test_save_null_string_attributes
173 topic = Topic.find(1)
174 topic.attributes = { "title" => "null", "author_name" => "null" }
177 assert_equal("null", topic.title)
178 assert_equal("null", topic.author_name)
181 def test_save_nil_string_attributes
182 topic = Topic.find(1)
186 assert_nil topic.title
189 def test_save_for_record_with_only_primary_key
190 minimalistic = Minimalistic.new
191 assert_nothing_raised { minimalistic.save }
194 def test_save_for_record_with_only_primary_key_that_is_provided
195 assert_nothing_raised { Minimalistic.create!(:id => 2) }
198 def test_hashes_not_mangled
199 new_topic = { :title => "New Topic" }
200 new_topic_values = { :title => "AnotherTopic" }
202 topic = Topic.new(new_topic)
203 assert_equal new_topic[:title], topic.title
205 topic.attributes= new_topic_values
206 assert_equal new_topic_values[:title], topic.title
210 topics = Topic.create([ { "title" => "first" }, { "title" => "second" }])
211 assert_equal 2, topics.size
212 assert_equal "first", topics.first.title
215 def test_create_columns_not_equal_attributes
217 topic.title = 'Another New Topic'
218 topic.send :write_attribute, 'does_not_exist', 'test'
219 assert_nothing_raised { topic.save }
222 def test_create_through_factory
223 topic = Topic.create("title" => "New Topic")
224 topicReloaded = Topic.find(topic.id)
225 assert_equal(topic, topicReloaded)
230 topic.title = "Another New Topic"
231 topic.written_on = "2003-12-12 23:23:00"
233 topicReloaded = Topic.find(topic.id)
234 assert_equal("Another New Topic", topicReloaded.title)
236 topicReloaded.title = "Updated topic"
239 topicReloadedAgain = Topic.find(topic.id)
241 assert_equal("Updated topic", topicReloadedAgain.title)
244 def test_update_columns_not_equal_attributes
246 topic.title = "Still another topic"
249 topicReloaded = Topic.find(topic.id)
250 topicReloaded.title = "A New Topic"
251 topicReloaded.send :write_attribute, 'does_not_exist', 'test'
252 assert_nothing_raised { topicReloaded.save }
255 def test_update_for_record_with_only_primary_key
256 minimalistic = minimalistics(:first)
257 assert_nothing_raised { minimalistic.save }
260 def test_write_attribute
262 topic.send(:write_attribute, :title, "Still another topic")
263 assert_equal "Still another topic", topic.title
265 topic.send(:write_attribute, "title", "Still another topic: part 2")
266 assert_equal "Still another topic: part 2", topic.title
269 def test_read_attribute
271 topic.title = "Don't change the topic"
272 assert_equal "Don't change the topic", topic.send(:read_attribute, "title")
273 assert_equal "Don't change the topic", topic["title"]
275 assert_equal "Don't change the topic", topic.send(:read_attribute, :title)
276 assert_equal "Don't change the topic", topic[:title]
279 def test_read_attribute_when_false
280 topic = topics(:first)
281 topic.approved = false
282 assert !topic.approved?, "approved should be false"
283 topic.approved = "false"
284 assert !topic.approved?, "approved should be false"
287 def test_read_attribute_when_true
288 topic = topics(:first)
289 topic.approved = true
290 assert topic.approved?, "approved should be true"
291 topic.approved = "true"
292 assert topic.approved?, "approved should be true"
295 def test_read_write_boolean_attribute
300 topic.approved = "false"
301 # puts "Expecting false"
303 assert !topic.approved?, "approved should be false"
304 topic.approved = "false"
305 # puts "Expecting false"
307 assert !topic.approved?, "approved should be false"
308 topic.approved = "true"
309 # puts "Expecting true"
311 assert topic.approved?, "approved should be true"
312 topic.approved = "true"
313 # puts "Expecting true"
315 assert topic.approved?, "approved should be true"
319 def test_query_attribute_string
320 [nil, "", " "].each do |value|
321 assert_equal false, Topic.new(:author_name => value).author_name?
324 assert_equal true, Topic.new(:author_name => "Name").author_name?
327 def test_query_attribute_number
328 [nil, 0, "0"].each do |value|
329 assert_equal false, Developer.new(:salary => value).salary?
332 assert_equal true, Developer.new(:salary => 1).salary?
333 assert_equal true, Developer.new(:salary => "1").salary?
336 def test_query_attribute_boolean
337 [nil, "", false, "false", "f", 0].each do |value|
338 assert_equal false, Topic.new(:approved => value).approved?
341 [true, "true", "1", 1].each do |value|
342 assert_equal true, Topic.new(:approved => value).approved?
346 def test_query_attribute_with_custom_fields
347 object = Company.find_by_sql(<<-SQL).first
348 SELECT c1.*, c2.ruby_type as string_value, c2.rating as int_value
349 FROM companies c1, companies c2
350 WHERE c1.firm_id = c2.id
354 assert_equal "Firm", object.string_value
355 assert object.string_value?
357 object.string_value = " "
358 assert !object.string_value?
360 assert_equal 1, object.int_value.to_i
361 assert object.int_value?
363 object.int_value = "0"
364 assert !object.int_value?
368 def test_reader_for_invalid_column_names
369 Topic.send(:define_read_method, "mumub-jumbo".to_sym, "mumub-jumbo", nil)
370 assert !Topic.generated_methods.include?("mumub-jumbo")
373 def test_non_attribute_access_and_assignment
375 assert !topic.respond_to?("mumbo")
376 assert_raises(NoMethodError) { topic.mumbo }
377 assert_raises(NoMethodError) { topic.mumbo = 5 }
380 def test_preserving_date_objects
381 # SQL Server doesn't have a separate column type just for dates, so all are returned as time
382 return true if current_adapter?(:SQLServerAdapter)
384 if current_adapter?(:SybaseAdapter, :OracleAdapter)
385 # Sybase ctlib does not (yet?) support the date type; use datetime instead.
386 # Oracle treats all dates/times as Time.
388 Time, Topic.find(1).last_read,
389 "The last_read attribute should be of the Time class"
393 Date, Topic.find(1).last_read,
394 "The last_read attribute should be of the Date class"
399 def test_preserving_time_objects
401 Time, Topic.find(1).bonus_time,
402 "The bonus_time attribute should be of the Time class"
406 Time, Topic.find(1).written_on,
407 "The written_on attribute should be of the Time class"
410 # For adapters which support microsecond resolution.
411 if current_adapter?(:PostgreSQLAdapter)
412 assert_equal 11, Topic.find(1).written_on.sec
413 assert_equal 223300, Topic.find(1).written_on.usec
414 assert_equal 9900, Topic.find(2).written_on.usec
418 def test_custom_mutator
419 topic = Topic.find(1)
420 # This mutator is protected in the class definition
421 topic.send(:approved=, true)
422 assert topic.instance_variable_get("@custom_approved")
426 topic = Topic.find(1)
427 assert_equal topic, topic.destroy, 'topic.destroy did not return self'
428 assert topic.frozen?, 'topic not frozen after destroy'
429 assert_raise(ActiveRecord::RecordNotFound) { Topic.find(topic.id) }
432 def test_record_not_found_exception
433 assert_raises(ActiveRecord::RecordNotFound) { topicReloaded = Topic.find(99999) }
436 def test_initialize_with_attributes
438 "title" => "initialized from attributes", "written_on" => "2003-12-12 23:23"
441 assert_equal("initialized from attributes", topic.title)
444 def test_initialize_with_invalid_attribute
446 topic = Topic.new({ "title" => "test",
447 "last_read(1i)" => "2005", "last_read(2i)" => "2", "last_read(3i)" => "31"})
448 rescue ActiveRecord::MultiparameterAssignmentErrors => ex
449 assert_equal(1, ex.errors.size)
450 assert_equal("last_read", ex.errors[0].attribute)
455 topics = Topic.find(:all, :order => 'id')
456 assert_equal(2, topics.size)
457 assert_equal(topics(:first).title, topics.first.title)
460 def test_load_with_condition
461 topics = Topic.find(:all, :conditions => "author_name = 'Mary'")
463 assert_equal(1, topics.size)
464 assert_equal(topics(:second).title, topics.first.title)
467 def test_table_name_guesses
468 classes = [Category, Smarts, CreditCard, CreditCard::PinNumber, CreditCard::PinNumber::CvvCode, CreditCard::SubPinNumber, CreditCard::Brand, MasterCreditCard]
470 assert_equal "topics", Topic.table_name
472 assert_equal "categories", Category.table_name
473 assert_equal "smarts", Smarts.table_name
474 assert_equal "credit_cards", CreditCard.table_name
475 assert_equal "credit_card_pin_numbers", CreditCard::PinNumber.table_name
476 assert_equal "credit_card_pin_number_cvv_codes", CreditCard::PinNumber::CvvCode.table_name
477 assert_equal "credit_card_pin_numbers", CreditCard::SubPinNumber.table_name
478 assert_equal "categories", CreditCard::Brand.table_name
479 assert_equal "master_credit_cards", MasterCreditCard.table_name
481 ActiveRecord::Base.pluralize_table_names = false
482 classes.each(&:reset_table_name)
484 assert_equal "category", Category.table_name
485 assert_equal "smarts", Smarts.table_name
486 assert_equal "credit_card", CreditCard.table_name
487 assert_equal "credit_card_pin_number", CreditCard::PinNumber.table_name
488 assert_equal "credit_card_pin_number_cvv_code", CreditCard::PinNumber::CvvCode.table_name
489 assert_equal "credit_card_pin_number", CreditCard::SubPinNumber.table_name
490 assert_equal "category", CreditCard::Brand.table_name
491 assert_equal "master_credit_card", MasterCreditCard.table_name
493 ActiveRecord::Base.pluralize_table_names = true
494 classes.each(&:reset_table_name)
496 ActiveRecord::Base.table_name_prefix = "test_"
497 Category.reset_table_name
498 assert_equal "test_categories", Category.table_name
499 ActiveRecord::Base.table_name_suffix = "_test"
500 Category.reset_table_name
501 assert_equal "test_categories_test", Category.table_name
502 ActiveRecord::Base.table_name_prefix = ""
503 Category.reset_table_name
504 assert_equal "categories_test", Category.table_name
505 ActiveRecord::Base.table_name_suffix = ""
506 Category.reset_table_name
507 assert_equal "categories", Category.table_name
509 ActiveRecord::Base.pluralize_table_names = false
510 ActiveRecord::Base.table_name_prefix = "test_"
511 Category.reset_table_name
512 assert_equal "test_category", Category.table_name
513 ActiveRecord::Base.table_name_suffix = "_test"
514 Category.reset_table_name
515 assert_equal "test_category_test", Category.table_name
516 ActiveRecord::Base.table_name_prefix = ""
517 Category.reset_table_name
518 assert_equal "category_test", Category.table_name
519 ActiveRecord::Base.table_name_suffix = ""
520 Category.reset_table_name
521 assert_equal "category", Category.table_name
523 ActiveRecord::Base.pluralize_table_names = true
524 classes.each(&:reset_table_name)
528 assert_equal 2, Topic.count
530 Topic.destroy_all "author_name = 'Mary'"
531 assert_equal 1, Topic.count
534 def test_destroy_many
535 assert_equal 3, Client.count
536 Client.destroy([2, 3])
537 assert_equal 1, Client.count
542 assert_equal 0, Topic.count
545 def test_boolean_attributes
546 assert ! Topic.find(1).approved?
547 assert Topic.find(2).approved?
550 def test_increment_counter
551 Topic.increment_counter("replies_count", 1)
552 assert_equal 2, Topic.find(1).replies_count
554 Topic.increment_counter("replies_count", 1)
555 assert_equal 3, Topic.find(1).replies_count
558 def test_decrement_counter
559 Topic.decrement_counter("replies_count", 2)
560 assert_equal -1, Topic.find(2).replies_count
562 Topic.decrement_counter("replies_count", 2)
563 assert_equal -2, Topic.find(2).replies_count
567 assert_equal 2, Topic.update_all("content = 'bulk updated!'")
568 assert_equal "bulk updated!", Topic.find(1).content
569 assert_equal "bulk updated!", Topic.find(2).content
571 assert_equal 2, Topic.update_all(['content = ?', 'bulk updated again!'])
572 assert_equal "bulk updated again!", Topic.find(1).content
573 assert_equal "bulk updated again!", Topic.find(2).content
575 assert_equal 2, Topic.update_all(['content = ?', nil])
576 assert_nil Topic.find(1).content
579 def test_update_all_with_hash
580 assert_not_nil Topic.find(1).last_read
581 assert_equal 2, Topic.update_all(:content => 'bulk updated with hash!', :last_read => nil)
582 assert_equal "bulk updated with hash!", Topic.find(1).content
583 assert_equal "bulk updated with hash!", Topic.find(2).content
584 assert_nil Topic.find(1).last_read
585 assert_nil Topic.find(2).last_read
588 if current_adapter?(:MysqlAdapter)
589 def test_update_all_with_order_and_limit
590 assert_equal 1, Topic.update_all("content = 'bulk updated!'", nil, :limit => 1, :order => 'id DESC')
595 topic_data = { 1 => { "content" => "1 updated" }, 2 => { "content" => "2 updated" } }
596 updated = Topic.update(topic_data.keys, topic_data.values)
598 assert_equal 2, updated.size
599 assert_equal "1 updated", Topic.find(1).content
600 assert_equal "2 updated", Topic.find(2).content
604 assert_equal 2, Topic.delete_all
607 def test_update_by_condition
608 Topic.update_all "content = 'bulk updated!'", ["approved = ?", true]
609 assert_equal "Have a nice day", Topic.find(1).content
610 assert_equal "bulk updated!", Topic.find(2).content
613 def test_attribute_present
615 t.title = "hello there!"
616 t.written_on = Time.now
617 assert t.attribute_present?("title")
618 assert t.attribute_present?("written_on")
619 assert !t.attribute_present?("content")
622 def test_attribute_keys_on_new_instance
624 assert_equal nil, t.title, "The topics table has a title column, so it should be nil"
625 assert_raise(NoMethodError) { t.title2 }
629 assert_equal "Firm", ActiveRecord::Base.class_name("firms")
630 assert_equal "Category", ActiveRecord::Base.class_name("categories")
631 assert_equal "AccountHolder", ActiveRecord::Base.class_name("account_holder")
633 ActiveRecord::Base.pluralize_table_names = false
634 assert_equal "Firms", ActiveRecord::Base.class_name( "firms" )
635 ActiveRecord::Base.pluralize_table_names = true
637 ActiveRecord::Base.table_name_prefix = "test_"
638 assert_equal "Firm", ActiveRecord::Base.class_name( "test_firms" )
639 ActiveRecord::Base.table_name_suffix = "_tests"
640 assert_equal "Firm", ActiveRecord::Base.class_name( "test_firms_tests" )
641 ActiveRecord::Base.table_name_prefix = ""
642 assert_equal "Firm", ActiveRecord::Base.class_name( "firms_tests" )
643 ActiveRecord::Base.table_name_suffix = ""
644 assert_equal "Firm", ActiveRecord::Base.class_name( "firms" )
648 assert_nil Topic.find(1).parent_id
649 assert_nil Topic.create("title" => "Hey you").parent_id
652 def test_default_values
654 assert topic.approved?
655 assert_nil topic.written_on
656 assert_nil topic.bonus_time
657 assert_nil topic.last_read
661 topic = Topic.find(topic.id)
662 assert topic.approved?
663 assert_nil topic.last_read
665 # Oracle has some funky default handling, so it requires a bit of
666 # extra testing. See ticket #2788.
667 if current_adapter?(:OracleAdapter)
668 test = TestOracleDefault.new
669 assert_equal "X", test.test_char
670 assert_equal "hello", test.test_string
671 assert_equal 3, test.test_int
675 # Oracle, SQLServer, and Sybase do not have a TIME datatype.
676 unless current_adapter?(:SQLServerAdapter, :OracleAdapter, :SybaseAdapter)
677 def test_utc_as_time_zone
678 Topic.default_timezone = :utc
679 attributes = { "bonus_time" => "5:42:00AM" }
680 topic = Topic.find(1)
681 topic.attributes = attributes
682 assert_equal Time.utc(2000, 1, 1, 5, 42, 0), topic.bonus_time
683 Topic.default_timezone = :local
686 def test_utc_as_time_zone_and_new
687 Topic.default_timezone = :utc
688 attributes = { "bonus_time(1i)"=>"2000",
689 "bonus_time(2i)"=>"1",
690 "bonus_time(3i)"=>"1",
691 "bonus_time(4i)"=>"10",
692 "bonus_time(5i)"=>"35",
693 "bonus_time(6i)"=>"50" }
694 topic = Topic.new(attributes)
695 assert_equal Time.utc(2000, 1, 1, 10, 35, 50), topic.bonus_time
696 Topic.default_timezone = :local
700 def test_default_values_on_empty_strings
703 topic.last_read = nil
707 topic = Topic.find(topic.id)
708 assert_nil topic.last_read
710 # Sybase adapter does not allow nulls in boolean columns
711 if current_adapter?(:SybaseAdapter)
712 assert topic.approved == false
714 assert_nil topic.approved
719 assert_equal Topic.find(1), Topic.find(2).topic
722 def test_equality_of_new_records
723 assert_not_equal Topic.new, Topic.new
727 assert_equal [ Topic.find(1) ], [ Topic.find(2).topic ] & [ Topic.find(1) ]
730 def test_destroy_new_record
733 assert client.frozen?
736 def test_destroy_record_with_associations
737 client = Client.find(3)
739 assert client.frozen?
740 assert_kind_of Firm, client.firm
741 assert_raises(TypeError) { client.name = "something else" }
744 def test_update_attribute
745 assert !Topic.find(1).approved?
746 Topic.find(1).update_attribute("approved", true)
747 assert Topic.find(1).approved?
749 Topic.find(1).update_attribute(:approved, false)
750 assert !Topic.find(1).approved?
753 def test_update_attributes
754 topic = Topic.find(1)
755 assert !topic.approved?
756 assert_equal "The First Topic", topic.title
758 topic.update_attributes("approved" => true, "title" => "The First Topic Updated")
760 assert topic.approved?
761 assert_equal "The First Topic Updated", topic.title
763 topic.update_attributes(:approved => false, :title => "The First Topic")
765 assert !topic.approved?
766 assert_equal "The First Topic", topic.title
769 def test_update_attributes!
770 reply = Reply.find(2)
771 assert_equal "The Second Topic's of the day", reply.title
772 assert_equal "Have a nice day", reply.content
774 reply.update_attributes!("title" => "The Second Topic's of the day updated", "content" => "Have a nice evening")
776 assert_equal "The Second Topic's of the day updated", reply.title
777 assert_equal "Have a nice evening", reply.content
779 reply.update_attributes!(:title => "The Second Topic's of the day", :content => "Have a nice day")
781 assert_equal "The Second Topic's of the day", reply.title
782 assert_equal "Have a nice day", reply.content
784 assert_raise(ActiveRecord::RecordInvalid) { reply.update_attributes!(:title => nil, :content => "Have a nice evening") }
787 def test_mass_assignment_should_raise_exception_if_accessible_and_protected_attribute_writers_are_both_used
788 topic = TopicWithProtectedContentAndAccessibleAuthorName.new
789 assert_raises(RuntimeError) { topic.attributes = { "author_name" => "me" } }
790 assert_raises(RuntimeError) { topic.attributes = { "content" => "stuff" } }
793 def test_mass_assignment_protection
795 firm.attributes = { "name" => "Next Angle", "rating" => 5 }
796 assert_equal 1, firm.rating
799 def test_mass_assignment_protection_against_class_attribute_writers
800 [:logger, :configurations, :primary_key_prefix_type, :table_name_prefix, :table_name_suffix, :pluralize_table_names, :colorize_logging,
801 :default_timezone, :allow_concurrency, :schema_format, :verification_timeout, :lock_optimistically, :record_timestamps].each do |method|
802 assert Task.respond_to?(method)
803 assert Task.respond_to?("#{method}=")
804 assert Task.new.respond_to?(method)
805 assert !Task.new.respond_to?("#{method}=")
809 def test_customized_primary_key_remains_protected
810 subscriber = Subscriber.new(:nick => 'webster123', :name => 'nice try')
811 assert_nil subscriber.id
813 keyboard = Keyboard.new(:key_number => 9, :name => 'nice try')
814 assert_nil keyboard.id
817 def test_customized_primary_key_remains_protected_when_referred_to_as_id
818 subscriber = Subscriber.new(:id => 'webster123', :name => 'nice try')
819 assert_nil subscriber.id
821 keyboard = Keyboard.new(:id => 9, :name => 'nice try')
822 assert_nil keyboard.id
825 def test_mass_assignment_protection_on_defaults
827 firm.attributes = { "id" => 5, "type" => "Client" }
829 assert_equal "Firm", firm[:type]
832 def test_mass_assignment_accessible
833 reply = Reply.new("title" => "hello", "content" => "world", "approved" => true)
836 assert reply.approved?
838 reply.approved = false
841 assert !reply.approved?
844 def test_mass_assignment_protection_inheritance
845 assert_nil LoosePerson.accessible_attributes
846 assert_equal [ :credit_rating, :administrator ], LoosePerson.protected_attributes
848 assert_nil LooseDescendant.accessible_attributes
849 assert_equal [ :credit_rating, :administrator, :phone_number ], LooseDescendant.protected_attributes
851 assert_nil TightPerson.protected_attributes
852 assert_equal [ :name, :address ], TightPerson.accessible_attributes
854 assert_nil TightDescendant.protected_attributes
855 assert_equal [ :name, :address, :phone_number ], TightDescendant.accessible_attributes
858 def test_readonly_attributes
859 assert_equal [ :title ], ReadonlyTitlePost.readonly_attributes
861 post = ReadonlyTitlePost.create(:title => "cannot change this", :body => "changeable")
863 assert_equal "cannot change this", post.title
865 post.update_attributes(:title => "try to change", :body => "changed")
867 assert_equal "cannot change this", post.title
868 assert_equal "changed", post.body
871 def test_multiparameter_attributes_on_date
872 attributes = { "last_read(1i)" => "2004", "last_read(2i)" => "6", "last_read(3i)" => "24" }
873 topic = Topic.find(1)
874 topic.attributes = attributes
875 # note that extra #to_date call allows test to pass for Oracle, which
876 # treats dates/times the same
877 assert_date_from_db Date.new(2004, 6, 24), topic.last_read.to_date
880 def test_multiparameter_attributes_on_date_with_empty_date
881 attributes = { "last_read(1i)" => "2004", "last_read(2i)" => "6", "last_read(3i)" => "" }
882 topic = Topic.find(1)
883 topic.attributes = attributes
884 # note that extra #to_date call allows test to pass for Oracle, which
885 # treats dates/times the same
886 assert_date_from_db Date.new(2004, 6, 1), topic.last_read.to_date
889 def test_multiparameter_attributes_on_date_with_all_empty
890 attributes = { "last_read(1i)" => "", "last_read(2i)" => "", "last_read(3i)" => "" }
891 topic = Topic.find(1)
892 topic.attributes = attributes
893 assert_nil topic.last_read
896 def test_multiparameter_attributes_on_time
898 "written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
899 "written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
901 topic = Topic.find(1)
902 topic.attributes = attributes
903 assert_equal Time.local(2004, 6, 24, 16, 24, 0), topic.written_on
906 def test_multiparameter_attributes_on_time_with_empty_seconds
908 "written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
909 "written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => ""
911 topic = Topic.find(1)
912 topic.attributes = attributes
913 assert_equal Time.local(2004, 6, 24, 16, 24, 0), topic.written_on
916 def test_multiparameter_mass_assignment_protector
918 time = Time.mktime(2000, 1, 1, 1)
920 attributes = { "starting(1i)" => "2004", "starting(2i)" => "6", "starting(3i)" => "24" }
921 task.attributes = attributes
922 assert_equal time, task.starting
925 def test_multiparameter_assignment_of_aggregation
926 customer = Customer.new
927 address = Address.new("The Street", "The City", "The Country")
928 attributes = { "address(1)" => address.street, "address(2)" => address.city, "address(3)" => address.country }
929 customer.attributes = attributes
930 assert_equal address, customer.address
933 def test_attributes_on_dummy_time
934 # Oracle, SQL Server, and Sybase do not have a TIME datatype.
935 return true if current_adapter?(:SQLServerAdapter, :OracleAdapter, :SybaseAdapter)
938 "bonus_time" => "5:42:00AM"
940 topic = Topic.find(1)
941 topic.attributes = attributes
942 assert_equal Time.local(2000, 1, 1, 5, 42, 0), topic.bonus_time
946 b_false = Booleantest.create({ "value" => false })
947 false_id = b_false.id
948 b_true = Booleantest.create({ "value" => true })
951 b_false = Booleantest.find(false_id)
952 assert !b_false.value?
953 b_true = Booleantest.find(true_id)
957 def test_boolean_cast_from_string
958 b_false = Booleantest.create({ "value" => "0" })
959 false_id = b_false.id
960 b_true = Booleantest.create({ "value" => "1" })
963 b_false = Booleantest.find(false_id)
964 assert !b_false.value?
965 b_true = Booleantest.find(true_id)
970 topic = Topic.find(1)
972 assert_nothing_raised { cloned_topic = topic.clone }
973 assert_equal topic.title, cloned_topic.title
974 assert cloned_topic.new_record?
976 # test if the attributes have been cloned
978 cloned_topic.title = "b"
979 assert_equal "a", topic.title
980 assert_equal "b", cloned_topic.title
982 # test if the attribute values have been cloned
983 topic.title = {"a" => "b"}
984 cloned_topic = topic.clone
985 cloned_topic.title["a"] = "c"
986 assert_equal "b", topic.title["a"]
988 #test if attributes set as part of after_initialize are cloned correctly
989 assert_equal topic.author_email_address, cloned_topic.author_email_address
991 # test if saved clone object differs from original
993 assert !cloned_topic.new_record?
994 assert cloned_topic.id != topic.id
997 def test_clone_with_aggregate_of_same_name_as_attribute
998 dev = DeveloperWithAggregate.find(1)
999 assert_kind_of DeveloperSalary, dev.salary
1002 assert_nothing_raised { clone = dev.clone }
1003 assert_kind_of DeveloperSalary, clone.salary
1004 assert_equal dev.salary.amount, clone.salary.amount
1005 assert clone.new_record?
1007 # test if the attributes have been cloned
1008 original_amount = clone.salary.amount
1009 dev.salary.amount = 1
1010 assert_equal original_amount, clone.salary.amount
1013 assert !clone.new_record?
1014 assert clone.id != dev.id
1017 def test_clone_preserves_subtype
1019 assert_nothing_raised { clone = Company.find(3).clone }
1020 assert_kind_of Client, clone
1024 company = Company.find(1)
1025 company.rating = 2147483647
1027 company = Company.find(1)
1028 assert_equal 2147483647, company.rating
1031 # TODO: extend defaults tests to other databases!
1032 if current_adapter?(:PostgreSQLAdapter)
1034 default = Default.new
1036 # fixed dates / times
1037 assert_equal Date.new(2004, 1, 1), default.fixed_date
1038 assert_equal Time.local(2004, 1,1,0,0,0,0), default.fixed_time
1041 assert_equal 'Y', default.char1
1042 assert_equal 'a varchar field', default.char2
1043 assert_equal 'a text field', default.char3
1046 class Geometric < ActiveRecord::Base; end
1047 def test_geometric_content
1049 # accepted format notes:
1050 # ()'s aren't required
1051 # values can be a mix of float or integer
1054 :a_point => '(5.0, 6.1)',
1055 #:a_line => '((2.0, 3), (5.5, 7.0))' # line type is currently unsupported in postgresql
1056 :a_line_segment => '(2.0, 3), (5.5, 7.0)',
1057 :a_box => '2.0, 3, 5.5, 7.0',
1058 :a_path => '[(2.0, 3), (5.5, 7.0), (8.5, 11.0)]', # [ ] is an open path
1059 :a_polygon => '((2.0, 3), (5.5, 7.0), (8.5, 11.0))',
1060 :a_circle => '<(5.3, 10.4), 2>'
1065 # Reload and check that we have all the geometric attributes.
1066 h = Geometric.find(g.id)
1068 assert_equal '(5,6.1)', h.a_point
1069 assert_equal '[(2,3),(5.5,7)]', h.a_line_segment
1070 assert_equal '(5.5,7),(2,3)', h.a_box # reordered to store upper right corner then bottom left corner
1071 assert_equal '[(2,3),(5.5,7),(8.5,11)]', h.a_path
1072 assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_polygon
1073 assert_equal '<(5.3,10.4),2>', h.a_circle
1075 # use a geometric function to test for an open path
1076 objs = Geometric.find_by_sql ["select isopen(a_path) from geometrics where id = ?", g.id]
1077 assert_equal objs[0].isopen, 't'
1079 # test alternate formats when defining the geometric types
1082 :a_point => '5.0, 6.1',
1083 #:a_line => '((2.0, 3), (5.5, 7.0))' # line type is currently unsupported in postgresql
1084 :a_line_segment => '((2.0, 3), (5.5, 7.0))',
1085 :a_box => '(2.0, 3), (5.5, 7.0)',
1086 :a_path => '((2.0, 3), (5.5, 7.0), (8.5, 11.0))', # ( ) is a closed path
1087 :a_polygon => '2.0, 3, 5.5, 7.0, 8.5, 11.0',
1088 :a_circle => '((5.3, 10.4), 2)'
1093 # Reload and check that we have all the geometric attributes.
1094 h = Geometric.find(g.id)
1096 assert_equal '(5,6.1)', h.a_point
1097 assert_equal '[(2,3),(5.5,7)]', h.a_line_segment
1098 assert_equal '(5.5,7),(2,3)', h.a_box # reordered to store upper right corner then bottom left corner
1099 assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_path
1100 assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_polygon
1101 assert_equal '<(5.3,10.4),2>', h.a_circle
1103 # use a geometric function to test for an closed path
1104 objs = Geometric.find_by_sql ["select isclosed(a_path) from geometrics where id = ?", g.id]
1105 assert_equal objs[0].isclosed, 't'
1109 class NumericData < ActiveRecord::Base
1110 self.table_name = 'numeric_data'
1113 def test_numeric_fields
1114 m = NumericData.new(
1115 :bank_balance => 1586.43,
1116 :big_bank_balance => BigDecimal("1000234000567.95"),
1117 :world_population => 6000000000,
1118 :my_house_population => 3
1122 m1 = NumericData.find(m.id)
1125 # As with migration_test.rb, we should make world_population >= 2**62
1126 # to cover 64-bit platforms and test it is a Bignum, but the main thing
1127 # is that it's an Integer.
1128 assert_kind_of Integer, m1.world_population
1129 assert_equal 6000000000, m1.world_population
1131 assert_kind_of Fixnum, m1.my_house_population
1132 assert_equal 3, m1.my_house_population
1134 assert_kind_of BigDecimal, m1.bank_balance
1135 assert_equal BigDecimal("1586.43"), m1.bank_balance
1137 assert_kind_of BigDecimal, m1.big_bank_balance
1138 assert_equal BigDecimal("1000234000567.95"), m1.big_bank_balance
1144 assert (auto.id > 0)
1147 def quote_column_name(name)
1153 source = {"foo" => "bar", "baz" => "quux"}
1154 actual = ar.send(:quote_columns, self, source)
1155 inverted = actual.invert
1156 assert_equal("<foo>", inverted["bar"])
1157 assert_equal("<baz>", inverted["quux"])
1160 def test_sql_injection_via_find
1161 assert_raises(ActiveRecord::RecordNotFound, ActiveRecord::StatementInvalid) do
1162 Topic.find("123456 OR id > 0")
1166 def test_column_name_properly_quoted
1167 col_record = ColumnName.new
1168 col_record.references = 40
1169 assert col_record.save
1170 col_record.references = 41
1171 assert col_record.save
1172 assert_not_nil c2 = ColumnName.find(col_record.id)
1173 assert_equal(41, c2.references)
1176 def test_quoting_arrays
1177 replies = Reply.find(:all, :conditions => [ "id IN (?)", topics(:first).replies.collect(&:id) ])
1178 assert_equal topics(:first).replies.size, replies.size
1180 replies = Reply.find(:all, :conditions => [ "id IN (?)", [] ])
1181 assert_equal 0, replies.size
1184 MyObject = Struct.new :attribute1, :attribute2
1186 def test_serialized_attribute
1187 myobj = MyObject.new('value1', 'value2')
1188 topic = Topic.create("content" => myobj)
1189 Topic.serialize("content", MyObject)
1190 assert_equal(myobj, topic.content)
1193 def test_nil_serialized_attribute_with_class_constraint
1194 myobj = MyObject.new('value1', 'value2')
1196 assert_nil topic.content
1199 def test_should_raise_exception_on_serialized_attribute_with_type_mismatch
1200 myobj = MyObject.new('value1', 'value2')
1201 topic = Topic.new(:content => myobj)
1203 Topic.serialize(:content, Hash)
1204 assert_raise(ActiveRecord::SerializationTypeMismatch) { Topic.find(topic.id).content }
1206 Topic.serialize(:content)
1209 def test_serialized_attribute_with_class_constraint
1210 settings = { "color" => "blue" }
1211 Topic.serialize(:content, Hash)
1212 topic = Topic.new(:content => settings)
1214 assert_equal(settings, Topic.find(topic.id).content)
1216 Topic.serialize(:content)
1220 author_name = "\\ \001 ' \n \\n \""
1221 topic = Topic.create('author_name' => author_name)
1222 assert_equal author_name, Topic.find(topic.id).author_name
1225 def test_quote_chars
1226 str = 'The Narrator'
1227 topic = Topic.create(:author_name => str)
1228 assert_equal str, topic.author_name
1230 assert_kind_of ActiveSupport::Multibyte::Chars, str.chars
1231 topic = Topic.find_by_author_name(str.chars)
1233 assert_kind_of Topic, topic
1234 assert_equal str, topic.author_name, "The right topic should have been found by name even with name passed as Chars"
1237 def test_class_level_destroy
1238 should_be_destroyed_reply = Reply.create("title" => "hello", "content" => "world")
1239 Topic.find(1).replies << should_be_destroyed_reply
1242 assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1) }
1243 assert_raise(ActiveRecord::RecordNotFound) { Reply.find(should_be_destroyed_reply.id) }
1246 def test_class_level_delete
1247 should_be_destroyed_reply = Reply.create("title" => "hello", "content" => "world")
1248 Topic.find(1).replies << should_be_destroyed_reply
1251 assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1) }
1252 assert_nothing_raised { Reply.find(should_be_destroyed_reply.id) }
1255 def test_increment_attribute
1256 assert_equal 50, accounts(:signals37).credit_limit
1257 accounts(:signals37).increment! :credit_limit
1258 assert_equal 51, accounts(:signals37, :reload).credit_limit
1260 accounts(:signals37).increment(:credit_limit).increment!(:credit_limit)
1261 assert_equal 53, accounts(:signals37, :reload).credit_limit
1264 def test_increment_nil_attribute
1265 assert_nil topics(:first).parent_id
1266 topics(:first).increment! :parent_id
1267 assert_equal 1, topics(:first).parent_id
1270 def test_decrement_attribute
1271 assert_equal 50, accounts(:signals37).credit_limit
1273 accounts(:signals37).decrement!(:credit_limit)
1274 assert_equal 49, accounts(:signals37, :reload).credit_limit
1276 accounts(:signals37).decrement(:credit_limit).decrement!(:credit_limit)
1277 assert_equal 47, accounts(:signals37, :reload).credit_limit
1280 def test_toggle_attribute
1281 assert !topics(:first).approved?
1282 topics(:first).toggle!(:approved)
1283 assert topics(:first).approved?
1284 topic = topics(:first)
1285 topic.toggle(:approved)
1286 assert !topic.approved?
1288 assert topic.approved?
1294 t1.title = "something else"
1297 assert_equal t1.title, t2.title
1300 def test_define_attr_method_with_value
1301 k = Class.new( ActiveRecord::Base )
1302 k.send(:define_attr_method, :table_name, "foo")
1303 assert_equal "foo", k.table_name
1306 def test_define_attr_method_with_block
1307 k = Class.new( ActiveRecord::Base )
1308 k.send(:define_attr_method, :primary_key) { "sys_" + original_primary_key }
1309 assert_equal "sys_id", k.primary_key
1312 def test_set_table_name_with_value
1313 k = Class.new( ActiveRecord::Base )
1314 k.table_name = "foo"
1315 assert_equal "foo", k.table_name
1316 k.set_table_name "bar"
1317 assert_equal "bar", k.table_name
1320 def test_set_table_name_with_block
1321 k = Class.new( ActiveRecord::Base )
1322 k.set_table_name { "ks" }
1323 assert_equal "ks", k.table_name
1326 def test_set_primary_key_with_value
1327 k = Class.new( ActiveRecord::Base )
1328 k.primary_key = "foo"
1329 assert_equal "foo", k.primary_key
1330 k.set_primary_key "bar"
1331 assert_equal "bar", k.primary_key
1334 def test_set_primary_key_with_block
1335 k = Class.new( ActiveRecord::Base )
1336 k.set_primary_key { "sys_" + original_primary_key }
1337 assert_equal "sys_id", k.primary_key
1340 def test_set_inheritance_column_with_value
1341 k = Class.new( ActiveRecord::Base )
1342 k.inheritance_column = "foo"
1343 assert_equal "foo", k.inheritance_column
1344 k.set_inheritance_column "bar"
1345 assert_equal "bar", k.inheritance_column
1348 def test_set_inheritance_column_with_block
1349 k = Class.new( ActiveRecord::Base )
1350 k.set_inheritance_column { original_inheritance_column + "_id" }
1351 assert_equal "type_id", k.inheritance_column
1354 def test_count_with_join
1355 res = Post.count_by_sql "SELECT COUNT(*) FROM posts LEFT JOIN comments ON posts.id=comments.post_id WHERE posts.#{QUOTED_TYPE} = 'Post'"
1357 res2 = Post.count(:conditions => "posts.#{QUOTED_TYPE} = 'Post'", :joins => "LEFT JOIN comments ON posts.id=comments.post_id")
1358 assert_equal res, res2
1361 assert_nothing_raised do
1362 res3 = Post.count(:conditions => "posts.#{QUOTED_TYPE} = 'Post'",
1363 :joins => "LEFT JOIN comments ON posts.id=comments.post_id")
1365 assert_equal res, res3
1367 res4 = Post.count_by_sql "SELECT COUNT(p.id) FROM posts p, comments co WHERE p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id"
1369 assert_nothing_raised do
1370 res5 = Post.count(:conditions => "p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id",
1371 :joins => "p, comments co",
1375 assert_equal res4, res5
1377 unless current_adapter?(:SQLite2Adapter, :DeprecatedSQLiteAdapter)
1378 res6 = Post.count_by_sql "SELECT COUNT(DISTINCT p.id) FROM posts p, comments co WHERE p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id"
1380 assert_nothing_raised do
1381 res7 = Post.count(:conditions => "p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id",
1382 :joins => "p, comments co",
1386 assert_equal res6, res7
1390 def test_clear_association_cache_stored
1392 assert_kind_of Firm, firm
1394 firm.clear_association_cache
1395 assert_equal Firm.find(1).clients.collect{ |x| x.name }.sort, firm.clients.collect{ |x| x.name }.sort
1398 def test_clear_association_cache_new_record
1400 client_stored = Client.find(3)
1401 client_new = Client.new
1402 client_new.name = "The Joneses"
1403 clients = [ client_stored, client_new ]
1405 firm.clients << clients
1406 assert_equal clients.map(&:name).to_set, firm.clients.map(&:name).to_set
1408 firm.clear_association_cache
1409 assert_equal clients.map(&:name).to_set, firm.clients.map(&:name).to_set
1412 def test_interpolate_sql
1413 assert_nothing_raised { Category.new.send(:interpolate_sql, 'foo@bar') }
1414 assert_nothing_raised { Category.new.send(:interpolate_sql, 'foo bar) baz') }
1415 assert_nothing_raised { Category.new.send(:interpolate_sql, 'foo bar} baz') }
1418 def test_scoped_find_conditions
1419 scoped_developers = Developer.with_scope(:find => { :conditions => 'salary > 90000' }) do
1420 Developer.find(:all, :conditions => 'id < 5')
1422 assert !scoped_developers.include?(developers(:david)) # David's salary is less than 90,000
1423 assert_equal 3, scoped_developers.size
1426 def test_scoped_find_limit_offset
1427 scoped_developers = Developer.with_scope(:find => { :limit => 3, :offset => 2 }) do
1428 Developer.find(:all, :order => 'id')
1430 assert !scoped_developers.include?(developers(:david))
1431 assert !scoped_developers.include?(developers(:jamis))
1432 assert_equal 3, scoped_developers.size
1434 # Test without scoped find conditions to ensure we get the whole thing
1435 developers = Developer.find(:all, :order => 'id')
1436 assert_equal Developer.count, developers.size
1439 def test_scoped_find_order
1440 # Test order in scope
1441 scoped_developers = Developer.with_scope(:find => { :limit => 1, :order => 'salary DESC' }) do
1442 Developer.find(:all)
1444 assert_equal 'Jamis', scoped_developers.first.name
1445 assert scoped_developers.include?(developers(:jamis))
1446 # Test scope without order and order in find
1447 scoped_developers = Developer.with_scope(:find => { :limit => 1 }) do
1448 Developer.find(:all, :order => 'salary DESC')
1450 # Test scope order + find order, find has priority
1451 scoped_developers = Developer.with_scope(:find => { :limit => 3, :order => 'id DESC' }) do
1452 Developer.find(:all, :order => 'salary ASC')
1454 assert scoped_developers.include?(developers(:poor_jamis))
1455 assert scoped_developers.include?(developers(:david))
1456 assert scoped_developers.include?(developers(:dev_10))
1457 # Test without scoped find conditions to ensure we get the right thing
1458 developers = Developer.find(:all, :order => 'id', :limit => 1)
1459 assert scoped_developers.include?(developers(:david))
1462 def test_scoped_find_limit_offset_including_has_many_association
1463 topics = Topic.with_scope(:find => {:limit => 1, :offset => 1, :include => :replies}) do
1464 Topic.find(:all, :order => "topics.id")
1466 assert_equal 1, topics.size
1467 assert_equal 2, topics.first.id
1470 def test_scoped_find_order_including_has_many_association
1471 developers = Developer.with_scope(:find => { :order => 'developers.salary DESC', :include => :projects }) do
1472 Developer.find(:all)
1474 assert developers.size >= 2
1475 for i in 1...developers.size
1476 assert developers[i-1].salary >= developers[i].salary
1480 def test_abstract_class
1481 assert !ActiveRecord::Base.abstract_class?
1482 assert LoosePerson.abstract_class?
1483 assert !LooseDescendant.abstract_class?
1487 assert_equal LoosePerson, LoosePerson.base_class
1488 assert_equal LooseDescendant, LooseDescendant.base_class
1489 assert_equal TightPerson, TightPerson.base_class
1490 assert_equal TightPerson, TightDescendant.base_class
1492 assert_equal Post, Post.base_class
1493 assert_equal Post, SpecialPost.base_class
1494 assert_equal Post, StiPost.base_class
1495 assert_equal SubStiPost, SubStiPost.base_class
1498 def test_descends_from_active_record
1499 # Tries to call Object.abstract_class?
1500 assert_raise(NoMethodError) do
1501 ActiveRecord::Base.descends_from_active_record?
1504 # Abstract subclass of AR::Base.
1505 assert LoosePerson.descends_from_active_record?
1507 # Concrete subclass of an abstract class.
1508 assert LooseDescendant.descends_from_active_record?
1510 # Concrete subclass of AR::Base.
1511 assert TightPerson.descends_from_active_record?
1513 # Concrete subclass of a concrete class but has no type column.
1514 assert TightDescendant.descends_from_active_record?
1516 # Concrete subclass of AR::Base.
1517 assert Post.descends_from_active_record?
1519 # Abstract subclass of a concrete class which has a type column.
1520 # This is pathological, as you'll never have Sub < Abstract < Concrete.
1521 assert !StiPost.descends_from_active_record?
1523 # Concrete subclasses an abstract class which has a type column.
1524 assert !SubStiPost.descends_from_active_record?
1527 def test_find_on_abstract_base_class_doesnt_use_type_condition
1528 old_class = LooseDescendant
1529 Object.send :remove_const, :LooseDescendant
1531 descendant = old_class.create!
1532 assert_not_nil LoosePerson.find(descendant.id), "Should have found instance of LooseDescendant when finding abstract LoosePerson: #{descendant.inspect}"
1534 unless Object.const_defined?(:LooseDescendant)
1535 Object.const_set :LooseDescendant, old_class
1539 def test_assert_queries
1540 query = lambda { ActiveRecord::Base.connection.execute 'select count(*) from developers' }
1541 assert_queries(2) { 2.times { query.call } }
1542 assert_queries 1, &query
1543 assert_no_queries { assert true }
1547 xml = REXML::Document.new(topics(:first).to_xml(:indent => 0))
1548 bonus_time_in_current_timezone = topics(:first).bonus_time.xmlschema
1549 written_on_in_current_timezone = topics(:first).written_on.xmlschema
1550 last_read_in_current_timezone = topics(:first).last_read.xmlschema
1552 assert_equal "topic", xml.root.name
1553 assert_equal "The First Topic" , xml.elements["//title"].text
1554 assert_equal "David" , xml.elements["//author-name"].text
1556 assert_equal "1", xml.elements["//id"].text
1557 assert_equal "integer" , xml.elements["//id"].attributes['type']
1559 assert_equal "1", xml.elements["//replies-count"].text
1560 assert_equal "integer" , xml.elements["//replies-count"].attributes['type']
1562 assert_equal written_on_in_current_timezone, xml.elements["//written-on"].text
1563 assert_equal "datetime" , xml.elements["//written-on"].attributes['type']
1565 assert_equal "--- Have a nice day\n" , xml.elements["//content"].text
1566 assert_equal "yaml" , xml.elements["//content"].attributes['type']
1568 assert_equal "david@loudthinking.com", xml.elements["//author-email-address"].text
1570 assert_equal nil, xml.elements["//parent-id"].text
1571 assert_equal "integer", xml.elements["//parent-id"].attributes['type']
1572 assert_equal "true", xml.elements["//parent-id"].attributes['nil']
1574 if current_adapter?(:SybaseAdapter, :SQLServerAdapter, :OracleAdapter)
1575 assert_equal last_read_in_current_timezone, xml.elements["//last-read"].text
1576 assert_equal "datetime" , xml.elements["//last-read"].attributes['type']
1578 assert_equal "2004-04-15", xml.elements["//last-read"].text
1579 assert_equal "date" , xml.elements["//last-read"].attributes['type']
1582 # Oracle and DB2 don't have true boolean or time-only fields
1583 unless current_adapter?(:OracleAdapter, :DB2Adapter)
1584 assert_equal "false", xml.elements["//approved"].text
1585 assert_equal "boolean" , xml.elements["//approved"].attributes['type']
1587 assert_equal bonus_time_in_current_timezone, xml.elements["//bonus-time"].text
1588 assert_equal "datetime" , xml.elements["//bonus-time"].attributes['type']
1592 def test_to_xml_skipping_attributes
1593 xml = topics(:first).to_xml(:indent => 0, :skip_instruct => true, :except => [:title, :replies_count])
1594 assert_equal "<topic>", xml.first(7)
1595 assert !xml.include?(%(<title>The First Topic</title>))
1596 assert xml.include?(%(<author-name>David</author-name>))
1598 xml = topics(:first).to_xml(:indent => 0, :skip_instruct => true, :except => [:title, :author_name, :replies_count])
1599 assert !xml.include?(%(<title>The First Topic</title>))
1600 assert !xml.include?(%(<author-name>David</author-name>))
1603 def test_to_xml_including_has_many_association
1604 xml = topics(:first).to_xml(:indent => 0, :skip_instruct => true, :include => :replies, :except => :replies_count)
1605 assert_equal "<topic>", xml.first(7)
1606 assert xml.include?(%(<replies type="array"><reply>))
1607 assert xml.include?(%(<title>The Second Topic's of the day</title>))
1610 def test_array_to_xml_including_has_many_association
1611 xml = [ topics(:first), topics(:second) ].to_xml(:indent => 0, :skip_instruct => true, :include => :replies)
1612 assert xml.include?(%(<replies type="array"><reply>))
1615 def test_array_to_xml_including_methods
1616 xml = [ topics(:first), topics(:second) ].to_xml(:indent => 0, :skip_instruct => true, :methods => [ :topic_id ])
1617 assert xml.include?(%(<topic-id type="integer">#{topics(:first).topic_id}</topic-id>)), xml
1618 assert xml.include?(%(<topic-id type="integer">#{topics(:second).topic_id}</topic-id>)), xml
1621 def test_array_to_xml_including_has_one_association
1622 xml = [ companies(:first_firm), companies(:rails_core) ].to_xml(:indent => 0, :skip_instruct => true, :include => :account)
1623 assert xml.include?(companies(:first_firm).account.to_xml(:indent => 0, :skip_instruct => true))
1624 assert xml.include?(companies(:rails_core).account.to_xml(:indent => 0, :skip_instruct => true))
1627 def test_array_to_xml_including_belongs_to_association
1628 xml = [ companies(:first_client), companies(:second_client), companies(:another_client) ].to_xml(:indent => 0, :skip_instruct => true, :include => :firm)
1629 assert xml.include?(companies(:first_client).to_xml(:indent => 0, :skip_instruct => true))
1630 assert xml.include?(companies(:second_client).firm.to_xml(:indent => 0, :skip_instruct => true))
1631 assert xml.include?(companies(:another_client).firm.to_xml(:indent => 0, :skip_instruct => true))
1634 def test_to_xml_including_belongs_to_association
1635 xml = companies(:first_client).to_xml(:indent => 0, :skip_instruct => true, :include => :firm)
1636 assert !xml.include?("<firm>")
1638 xml = companies(:second_client).to_xml(:indent => 0, :skip_instruct => true, :include => :firm)
1639 assert xml.include?("<firm>")
1642 def test_to_xml_including_multiple_associations
1643 xml = companies(:first_firm).to_xml(:indent => 0, :skip_instruct => true, :include => [ :clients, :account ])
1644 assert_equal "<firm>", xml.first(6)
1645 assert xml.include?(%(<account>))
1646 assert xml.include?(%(<clients type="array"><client>))
1649 def test_to_xml_including_multiple_associations_with_options
1650 xml = companies(:first_firm).to_xml(
1651 :indent => 0, :skip_instruct => true,
1652 :include => { :clients => { :only => :name } }
1655 assert_equal "<firm>", xml.first(6)
1656 assert xml.include?(%(<client><name>Summit</name></client>))
1657 assert xml.include?(%(<clients type="array"><client>))
1660 def test_to_xml_including_methods
1661 xml = Company.new.to_xml(:methods => :arbitrary_method, :skip_instruct => true)
1662 assert_equal "<company>", xml.first(9)
1663 assert xml.include?(%(<arbitrary-method>I am Jack's profound disappointment</arbitrary-method>))
1666 def test_to_xml_with_block
1667 value = "Rockin' the block"
1668 xml = Company.new.to_xml(:skip_instruct => true) do |xml|
1669 xml.tag! "arbitrary-element", value
1671 assert_equal "<company>", xml.first(9)
1672 assert xml.include?(%(<arbitrary-element>#{value}</arbitrary-element>))
1675 def test_except_attributes
1677 %w( author_name type id approved replies_count bonus_time written_on content author_email_address parent_id last_read),
1678 topics(:first).attributes(:except => :title).keys
1682 %w( replies_count bonus_time written_on content author_email_address parent_id last_read),
1683 topics(:first).attributes(:except => [ :title, :id, :type, :approved, :author_name ]).keys
1687 def test_include_attributes
1688 assert_equal(%w( title ), topics(:first).attributes(:only => :title).keys)
1689 assert_equal(%w( title author_name type id approved ), topics(:first).attributes(:only => [ :title, :id, :type, :approved, :author_name ]).keys)
1692 def test_type_name_with_module_should_handle_beginning
1693 assert_equal 'ActiveRecord::Person', ActiveRecord::Base.send(:type_name_with_module, 'Person')
1694 assert_equal '::Person', ActiveRecord::Base.send(:type_name_with_module, '::Person')
1697 def test_to_param_should_return_string
1698 assert_kind_of String, Client.find(:first).to_param
1701 def test_inspect_class
1702 assert_equal 'ActiveRecord::Base', ActiveRecord::Base.inspect
1703 assert_equal 'LoosePerson(abstract)', LoosePerson.inspect
1704 assert_match(/^Topic\(id: integer, title: string/, Topic.inspect)
1707 def test_inspect_instance
1708 topic = topics(:first)
1709 assert_equal %(#<Topic id: 1, title: "The First Topic", author_name: "David", author_email_address: "david@loudthinking.com", written_on: "#{topic.written_on.to_s(:db)}", bonus_time: "#{topic.bonus_time.to_s(:db)}", last_read: "#{topic.last_read.to_s(:db)}", content: "Have a nice day", approved: false, replies_count: 1, parent_id: nil, type: nil>), topic.inspect
1712 def test_inspect_new_instance
1713 assert_match /Topic id: nil/, Topic.new.inspect
1716 def test_inspect_limited_select_instance
1717 assert_equal %(#<Topic id: 1>), Topic.find(:first, :select => 'id', :conditions => 'id = 1').inspect
1718 assert_equal %(#<Topic id: 1, title: "The First Topic">), Topic.find(:first, :select => 'id, title', :conditions => 'id = 1').inspect
1721 def test_inspect_class_without_table
1722 assert_equal "NonExistentTable(Table doesn't exist)", NonExistentTable.inspect
1725 def test_attribute_for_inspect
1727 t.content = %(This is some really long content, longer than 50 characters, so I can test that text is truncated correctly by the new ActiveRecord::Base#inspect method! Yay! BOOM!)
1729 assert_equal %("#{t.written_on.to_s(:db)}"), t.attribute_for_inspect(:written_on)
1730 assert_equal '"This is some really long content, longer than 50 ch..."', t.attribute_for_inspect(:content)