PageRenderTime 61ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/rails/activerecord/test/base_test.rb

http://github.com/benburkert/cruisecontrolrb
Ruby | 1586 lines | 1382 code | 158 blank | 46 comment | 11 complexity | 4d590762efa69bd85249d8f6808545d1 MD5 | raw file
Possible License(s): Apache-2.0

Large files files are truncated, but you can click here to view the full file

  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. class Category < ActiveRecord::Base; end
  15. class Smarts < ActiveRecord::Base; end
  16. class CreditCard < ActiveRecord::Base
  17. class PinNumber < ActiveRecord::Base
  18. class CvvCode < ActiveRecord::Base; end
  19. class SubCvvCode < CvvCode; end
  20. end
  21. class SubPinNumber < PinNumber; end
  22. class Brand < Category; end
  23. end
  24. class MasterCreditCard < ActiveRecord::Base; end
  25. class Post < ActiveRecord::Base; end
  26. class Computer < ActiveRecord::Base; end
  27. class NonExistentTable < ActiveRecord::Base; end
  28. class TestOracleDefault < ActiveRecord::Base; end
  29. class LoosePerson < ActiveRecord::Base
  30. self.table_name = 'people'
  31. self.abstract_class = true
  32. attr_protected :credit_rating, :administrator
  33. end
  34. class LooseDescendant < LoosePerson
  35. attr_protected :phone_number
  36. end
  37. class TightPerson < ActiveRecord::Base
  38. self.table_name = 'people'
  39. attr_accessible :name, :address
  40. end
  41. class TightDescendant < TightPerson
  42. attr_accessible :phone_number
  43. end
  44. class Booleantest < ActiveRecord::Base; end
  45. class Task < ActiveRecord::Base
  46. attr_protected :starting
  47. end
  48. class BasicsTest < Test::Unit::TestCase
  49. fixtures :topics, :companies, :developers, :projects, :computers, :accounts
  50. def test_table_exists
  51. assert !NonExistentTable.table_exists?
  52. assert Topic.table_exists?
  53. end
  54. def test_set_attributes
  55. topic = Topic.find(1)
  56. topic.attributes = { "title" => "Budget", "author_name" => "Jason" }
  57. topic.save
  58. assert_equal("Budget", topic.title)
  59. assert_equal("Jason", topic.author_name)
  60. assert_equal(topics(:first).author_email_address, Topic.find(1).author_email_address)
  61. end
  62. def test_integers_as_nil
  63. test = AutoId.create('value' => '')
  64. assert_nil AutoId.find(test.id).value
  65. end
  66. def test_set_attributes_with_block
  67. topic = Topic.new do |t|
  68. t.title = "Budget"
  69. t.author_name = "Jason"
  70. end
  71. assert_equal("Budget", topic.title)
  72. assert_equal("Jason", topic.author_name)
  73. end
  74. def test_respond_to?
  75. topic = Topic.find(1)
  76. assert topic.respond_to?("title")
  77. assert topic.respond_to?("title?")
  78. assert topic.respond_to?("title=")
  79. assert topic.respond_to?(:title)
  80. assert topic.respond_to?(:title?)
  81. assert topic.respond_to?(:title=)
  82. assert topic.respond_to?("author_name")
  83. assert topic.respond_to?("attribute_names")
  84. assert !topic.respond_to?("nothingness")
  85. assert !topic.respond_to?(:nothingness)
  86. end
  87. def test_array_content
  88. topic = Topic.new
  89. topic.content = %w( one two three )
  90. topic.save
  91. assert_equal(%w( one two three ), Topic.find(topic.id).content)
  92. end
  93. def test_hash_content
  94. topic = Topic.new
  95. topic.content = { "one" => 1, "two" => 2 }
  96. topic.save
  97. assert_equal 2, Topic.find(topic.id).content["two"]
  98. topic.content["three"] = 3
  99. topic.save
  100. assert_equal 3, Topic.find(topic.id).content["three"]
  101. end
  102. def test_update_array_content
  103. topic = Topic.new
  104. topic.content = %w( one two three )
  105. topic.content.push "four"
  106. assert_equal(%w( one two three four ), topic.content)
  107. topic.save
  108. topic = Topic.find(topic.id)
  109. topic.content << "five"
  110. assert_equal(%w( one two three four five ), topic.content)
  111. end
  112. def test_case_sensitive_attributes_hash
  113. # DB2 is not case-sensitive
  114. return true if current_adapter?(:DB2Adapter)
  115. assert_equal @loaded_fixtures['computers']['workstation'].to_hash, Computer.find(:first).attributes
  116. end
  117. def test_create
  118. topic = Topic.new
  119. topic.title = "New Topic"
  120. topic.save
  121. topic_reloaded = Topic.find(topic.id)
  122. assert_equal("New Topic", topic_reloaded.title)
  123. end
  124. def test_save!
  125. topic = Topic.new(:title => "New Topic")
  126. assert topic.save!
  127. reply = Reply.new
  128. assert_raise(ActiveRecord::RecordInvalid) { reply.save! }
  129. end
  130. def test_save_null_string_attributes
  131. topic = Topic.find(1)
  132. topic.attributes = { "title" => "null", "author_name" => "null" }
  133. topic.save!
  134. topic.reload
  135. assert_equal("null", topic.title)
  136. assert_equal("null", topic.author_name)
  137. end
  138. def test_save_nil_string_attributes
  139. topic = Topic.find(1)
  140. topic.title = nil
  141. topic.save!
  142. topic.reload
  143. assert_nil topic.title
  144. end
  145. def test_hashes_not_mangled
  146. new_topic = { :title => "New Topic" }
  147. new_topic_values = { :title => "AnotherTopic" }
  148. topic = Topic.new(new_topic)
  149. assert_equal new_topic[:title], topic.title
  150. topic.attributes= new_topic_values
  151. assert_equal new_topic_values[:title], topic.title
  152. end
  153. def test_create_many
  154. topics = Topic.create([ { "title" => "first" }, { "title" => "second" }])
  155. assert_equal 2, topics.size
  156. assert_equal "first", topics.first.title
  157. end
  158. def test_create_columns_not_equal_attributes
  159. topic = Topic.new
  160. topic.title = 'Another New Topic'
  161. topic.send :write_attribute, 'does_not_exist', 'test'
  162. assert_nothing_raised { topic.save }
  163. end
  164. def test_create_through_factory
  165. topic = Topic.create("title" => "New Topic")
  166. topicReloaded = Topic.find(topic.id)
  167. assert_equal(topic, topicReloaded)
  168. end
  169. def test_update
  170. topic = Topic.new
  171. topic.title = "Another New Topic"
  172. topic.written_on = "2003-12-12 23:23:00"
  173. topic.save
  174. topicReloaded = Topic.find(topic.id)
  175. assert_equal("Another New Topic", topicReloaded.title)
  176. topicReloaded.title = "Updated topic"
  177. topicReloaded.save
  178. topicReloadedAgain = Topic.find(topic.id)
  179. assert_equal("Updated topic", topicReloadedAgain.title)
  180. end
  181. def test_update_columns_not_equal_attributes
  182. topic = Topic.new
  183. topic.title = "Still another topic"
  184. topic.save
  185. topicReloaded = Topic.find(topic.id)
  186. topicReloaded.title = "A New Topic"
  187. topicReloaded.send :write_attribute, 'does_not_exist', 'test'
  188. assert_nothing_raised { topicReloaded.save }
  189. end
  190. def test_write_attribute
  191. topic = Topic.new
  192. topic.send(:write_attribute, :title, "Still another topic")
  193. assert_equal "Still another topic", topic.title
  194. topic.send(:write_attribute, "title", "Still another topic: part 2")
  195. assert_equal "Still another topic: part 2", topic.title
  196. end
  197. def test_read_attribute
  198. topic = Topic.new
  199. topic.title = "Don't change the topic"
  200. assert_equal "Don't change the topic", topic.send(:read_attribute, "title")
  201. assert_equal "Don't change the topic", topic["title"]
  202. assert_equal "Don't change the topic", topic.send(:read_attribute, :title)
  203. assert_equal "Don't change the topic", topic[:title]
  204. end
  205. def test_read_attribute_when_false
  206. topic = topics(:first)
  207. topic.approved = false
  208. assert !topic.approved?, "approved should be false"
  209. topic.approved = "false"
  210. assert !topic.approved?, "approved should be false"
  211. end
  212. def test_read_attribute_when_true
  213. topic = topics(:first)
  214. topic.approved = true
  215. assert topic.approved?, "approved should be true"
  216. topic.approved = "true"
  217. assert topic.approved?, "approved should be true"
  218. end
  219. def test_read_write_boolean_attribute
  220. topic = Topic.new
  221. # puts ""
  222. # puts "New Topic"
  223. # puts topic.inspect
  224. topic.approved = "false"
  225. # puts "Expecting false"
  226. # puts topic.inspect
  227. assert !topic.approved?, "approved should be false"
  228. topic.approved = "false"
  229. # puts "Expecting false"
  230. # puts topic.inspect
  231. assert !topic.approved?, "approved should be false"
  232. topic.approved = "true"
  233. # puts "Expecting true"
  234. # puts topic.inspect
  235. assert topic.approved?, "approved should be true"
  236. topic.approved = "true"
  237. # puts "Expecting true"
  238. # puts topic.inspect
  239. assert topic.approved?, "approved should be true"
  240. # puts ""
  241. end
  242. def test_reader_generation
  243. Topic.find(:first).title
  244. Firm.find(:first).name
  245. Client.find(:first).name
  246. if ActiveRecord::Base.generate_read_methods
  247. assert_readers(Topic, %w(type replies_count))
  248. assert_readers(Firm, %w(type))
  249. assert_readers(Client, %w(type ruby_type rating?))
  250. else
  251. [Topic, Firm, Client].each {|klass| assert_equal klass.read_methods, {}}
  252. end
  253. end
  254. def test_reader_for_invalid_column_names
  255. # column names which aren't legal ruby ids
  256. topic = Topic.find(:first)
  257. topic.send(:define_read_method, "mumub-jumbo".to_sym, "mumub-jumbo", nil)
  258. assert !Topic.read_methods.include?("mumub-jumbo")
  259. end
  260. def test_non_attribute_access_and_assignment
  261. topic = Topic.new
  262. assert !topic.respond_to?("mumbo")
  263. assert_raises(NoMethodError) { topic.mumbo }
  264. assert_raises(NoMethodError) { topic.mumbo = 5 }
  265. end
  266. def test_preserving_date_objects
  267. # SQL Server doesn't have a separate column type just for dates, so all are returned as time
  268. return true if current_adapter?(:SQLServerAdapter)
  269. if current_adapter?(:SybaseAdapter)
  270. # Sybase ctlib does not (yet?) support the date type; use datetime instead.
  271. assert_kind_of(
  272. Time, Topic.find(1).last_read,
  273. "The last_read attribute should be of the Time class"
  274. )
  275. else
  276. assert_kind_of(
  277. Date, Topic.find(1).last_read,
  278. "The last_read attribute should be of the Date class"
  279. )
  280. end
  281. end
  282. def test_preserving_time_objects
  283. assert_kind_of(
  284. Time, Topic.find(1).bonus_time,
  285. "The bonus_time attribute should be of the Time class"
  286. )
  287. assert_kind_of(
  288. Time, Topic.find(1).written_on,
  289. "The written_on attribute should be of the Time class"
  290. )
  291. # For adapters which support microsecond resolution.
  292. if current_adapter?(:PostgreSQLAdapter)
  293. assert_equal 11, Topic.find(1).written_on.sec
  294. assert_equal 223300, Topic.find(1).written_on.usec
  295. assert_equal 9900, Topic.find(2).written_on.usec
  296. end
  297. end
  298. def test_destroy
  299. topic = Topic.find(1)
  300. assert_equal topic, topic.destroy, 'topic.destroy did not return self'
  301. assert topic.frozen?, 'topic not frozen after destroy'
  302. assert_raise(ActiveRecord::RecordNotFound) { Topic.find(topic.id) }
  303. end
  304. def test_record_not_found_exception
  305. assert_raises(ActiveRecord::RecordNotFound) { topicReloaded = Topic.find(99999) }
  306. end
  307. def test_initialize_with_attributes
  308. topic = Topic.new({
  309. "title" => "initialized from attributes", "written_on" => "2003-12-12 23:23"
  310. })
  311. assert_equal("initialized from attributes", topic.title)
  312. end
  313. def test_initialize_with_invalid_attribute
  314. begin
  315. topic = Topic.new({ "title" => "test",
  316. "last_read(1i)" => "2005", "last_read(2i)" => "2", "last_read(3i)" => "31"})
  317. rescue ActiveRecord::MultiparameterAssignmentErrors => ex
  318. assert_equal(1, ex.errors.size)
  319. assert_equal("last_read", ex.errors[0].attribute)
  320. end
  321. end
  322. def test_load
  323. topics = Topic.find(:all, :order => 'id')
  324. assert_equal(2, topics.size)
  325. assert_equal(topics(:first).title, topics.first.title)
  326. end
  327. def test_load_with_condition
  328. topics = Topic.find(:all, :conditions => "author_name = 'Mary'")
  329. assert_equal(1, topics.size)
  330. assert_equal(topics(:second).title, topics.first.title)
  331. end
  332. def test_table_name_guesses
  333. classes = [Category, Smarts, CreditCard, CreditCard::PinNumber, CreditCard::PinNumber::CvvCode, CreditCard::SubPinNumber, CreditCard::Brand, MasterCreditCard]
  334. assert_equal "topics", Topic.table_name
  335. assert_equal "categories", Category.table_name
  336. assert_equal "smarts", Smarts.table_name
  337. assert_equal "credit_cards", CreditCard.table_name
  338. assert_equal "credit_card_pin_numbers", CreditCard::PinNumber.table_name
  339. assert_equal "credit_card_pin_number_cvv_codes", CreditCard::PinNumber::CvvCode.table_name
  340. assert_equal "credit_card_pin_numbers", CreditCard::SubPinNumber.table_name
  341. assert_equal "categories", CreditCard::Brand.table_name
  342. assert_equal "master_credit_cards", MasterCreditCard.table_name
  343. ActiveRecord::Base.pluralize_table_names = false
  344. classes.each(&:reset_table_name)
  345. assert_equal "category", Category.table_name
  346. assert_equal "smarts", Smarts.table_name
  347. assert_equal "credit_card", CreditCard.table_name
  348. assert_equal "credit_card_pin_number", CreditCard::PinNumber.table_name
  349. assert_equal "credit_card_pin_number_cvv_code", CreditCard::PinNumber::CvvCode.table_name
  350. assert_equal "credit_card_pin_number", CreditCard::SubPinNumber.table_name
  351. assert_equal "category", CreditCard::Brand.table_name
  352. assert_equal "master_credit_card", MasterCreditCard.table_name
  353. ActiveRecord::Base.pluralize_table_names = true
  354. classes.each(&:reset_table_name)
  355. ActiveRecord::Base.table_name_prefix = "test_"
  356. Category.reset_table_name
  357. assert_equal "test_categories", Category.table_name
  358. ActiveRecord::Base.table_name_suffix = "_test"
  359. Category.reset_table_name
  360. assert_equal "test_categories_test", Category.table_name
  361. ActiveRecord::Base.table_name_prefix = ""
  362. Category.reset_table_name
  363. assert_equal "categories_test", Category.table_name
  364. ActiveRecord::Base.table_name_suffix = ""
  365. Category.reset_table_name
  366. assert_equal "categories", Category.table_name
  367. ActiveRecord::Base.pluralize_table_names = false
  368. ActiveRecord::Base.table_name_prefix = "test_"
  369. Category.reset_table_name
  370. assert_equal "test_category", Category.table_name
  371. ActiveRecord::Base.table_name_suffix = "_test"
  372. Category.reset_table_name
  373. assert_equal "test_category_test", Category.table_name
  374. ActiveRecord::Base.table_name_prefix = ""
  375. Category.reset_table_name
  376. assert_equal "category_test", Category.table_name
  377. ActiveRecord::Base.table_name_suffix = ""
  378. Category.reset_table_name
  379. assert_equal "category", Category.table_name
  380. ActiveRecord::Base.pluralize_table_names = true
  381. classes.each(&:reset_table_name)
  382. end
  383. def test_destroy_all
  384. assert_equal 2, Topic.count
  385. Topic.destroy_all "author_name = 'Mary'"
  386. assert_equal 1, Topic.count
  387. end
  388. def test_destroy_many
  389. assert_equal 3, Client.count
  390. Client.destroy([2, 3])
  391. assert_equal 1, Client.count
  392. end
  393. def test_delete_many
  394. Topic.delete([1, 2])
  395. assert_equal 0, Topic.count
  396. end
  397. def test_boolean_attributes
  398. assert ! Topic.find(1).approved?
  399. assert Topic.find(2).approved?
  400. end
  401. def test_increment_counter
  402. Topic.increment_counter("replies_count", 1)
  403. assert_equal 2, Topic.find(1).replies_count
  404. Topic.increment_counter("replies_count", 1)
  405. assert_equal 3, Topic.find(1).replies_count
  406. end
  407. def test_decrement_counter
  408. Topic.decrement_counter("replies_count", 2)
  409. assert_equal -1, Topic.find(2).replies_count
  410. Topic.decrement_counter("replies_count", 2)
  411. assert_equal -2, Topic.find(2).replies_count
  412. end
  413. def test_update_all
  414. # The ADO library doesn't support the number of affected rows
  415. return true if current_adapter?(:SQLServerAdapter)
  416. assert_equal 2, Topic.update_all("content = 'bulk updated!'")
  417. assert_equal "bulk updated!", Topic.find(1).content
  418. assert_equal "bulk updated!", Topic.find(2).content
  419. assert_equal 2, Topic.update_all(['content = ?', 'bulk updated again!'])
  420. assert_equal "bulk updated again!", Topic.find(1).content
  421. assert_equal "bulk updated again!", Topic.find(2).content
  422. end
  423. def test_update_many
  424. topic_data = { 1 => { "content" => "1 updated" }, 2 => { "content" => "2 updated" } }
  425. updated = Topic.update(topic_data.keys, topic_data.values)
  426. assert_equal 2, updated.size
  427. assert_equal "1 updated", Topic.find(1).content
  428. assert_equal "2 updated", Topic.find(2).content
  429. end
  430. def test_delete_all
  431. # The ADO library doesn't support the number of affected rows
  432. return true if current_adapter?(:SQLServerAdapter)
  433. assert_equal 2, Topic.delete_all
  434. end
  435. def test_update_by_condition
  436. Topic.update_all "content = 'bulk updated!'", ["approved = ?", true]
  437. assert_equal "Have a nice day", Topic.find(1).content
  438. assert_equal "bulk updated!", Topic.find(2).content
  439. end
  440. def test_attribute_present
  441. t = Topic.new
  442. t.title = "hello there!"
  443. t.written_on = Time.now
  444. assert t.attribute_present?("title")
  445. assert t.attribute_present?("written_on")
  446. assert !t.attribute_present?("content")
  447. end
  448. def test_attribute_keys_on_new_instance
  449. t = Topic.new
  450. assert_equal nil, t.title, "The topics table has a title column, so it should be nil"
  451. assert_raise(NoMethodError) { t.title2 }
  452. end
  453. def test_class_name
  454. assert_equal "Firm", ActiveRecord::Base.class_name("firms")
  455. assert_equal "Category", ActiveRecord::Base.class_name("categories")
  456. assert_equal "AccountHolder", ActiveRecord::Base.class_name("account_holder")
  457. ActiveRecord::Base.pluralize_table_names = false
  458. assert_equal "Firms", ActiveRecord::Base.class_name( "firms" )
  459. ActiveRecord::Base.pluralize_table_names = true
  460. ActiveRecord::Base.table_name_prefix = "test_"
  461. assert_equal "Firm", ActiveRecord::Base.class_name( "test_firms" )
  462. ActiveRecord::Base.table_name_suffix = "_tests"
  463. assert_equal "Firm", ActiveRecord::Base.class_name( "test_firms_tests" )
  464. ActiveRecord::Base.table_name_prefix = ""
  465. assert_equal "Firm", ActiveRecord::Base.class_name( "firms_tests" )
  466. ActiveRecord::Base.table_name_suffix = ""
  467. assert_equal "Firm", ActiveRecord::Base.class_name( "firms" )
  468. end
  469. def test_null_fields
  470. assert_nil Topic.find(1).parent_id
  471. assert_nil Topic.create("title" => "Hey you").parent_id
  472. end
  473. def test_default_values
  474. topic = Topic.new
  475. assert topic.approved?
  476. assert_nil topic.written_on
  477. assert_nil topic.bonus_time
  478. assert_nil topic.last_read
  479. topic.save
  480. topic = Topic.find(topic.id)
  481. assert topic.approved?
  482. assert_nil topic.last_read
  483. # Oracle has some funky default handling, so it requires a bit of
  484. # extra testing. See ticket #2788.
  485. if current_adapter?(:OracleAdapter)
  486. test = TestOracleDefault.new
  487. assert_equal "X", test.test_char
  488. assert_equal "hello", test.test_string
  489. assert_equal 3, test.test_int
  490. end
  491. end
  492. # Oracle, SQLServer, and Sybase do not have a TIME datatype.
  493. unless current_adapter?(:SQLServerAdapter, :OracleAdapter, :SybaseAdapter)
  494. def test_utc_as_time_zone
  495. Topic.default_timezone = :utc
  496. attributes = { "bonus_time" => "5:42:00AM" }
  497. topic = Topic.find(1)
  498. topic.attributes = attributes
  499. assert_equal Time.utc(2000, 1, 1, 5, 42, 0), topic.bonus_time
  500. Topic.default_timezone = :local
  501. end
  502. def test_utc_as_time_zone_and_new
  503. Topic.default_timezone = :utc
  504. attributes = { "bonus_time(1i)"=>"2000",
  505. "bonus_time(2i)"=>"1",
  506. "bonus_time(3i)"=>"1",
  507. "bonus_time(4i)"=>"10",
  508. "bonus_time(5i)"=>"35",
  509. "bonus_time(6i)"=>"50" }
  510. topic = Topic.new(attributes)
  511. assert_equal Time.utc(2000, 1, 1, 10, 35, 50), topic.bonus_time
  512. Topic.default_timezone = :local
  513. end
  514. end
  515. def test_default_values_on_empty_strings
  516. topic = Topic.new
  517. topic.approved = nil
  518. topic.last_read = nil
  519. topic.save
  520. topic = Topic.find(topic.id)
  521. assert_nil topic.last_read
  522. # Sybase adapter does not allow nulls in boolean columns
  523. if current_adapter?(:SybaseAdapter)
  524. assert topic.approved == false
  525. else
  526. assert_nil topic.approved
  527. end
  528. end
  529. def test_equality
  530. assert_equal Topic.find(1), Topic.find(2).topic
  531. end
  532. def test_equality_of_new_records
  533. assert_not_equal Topic.new, Topic.new
  534. end
  535. def test_hashing
  536. assert_equal [ Topic.find(1) ], [ Topic.find(2).topic ] & [ Topic.find(1) ]
  537. end
  538. def test_destroy_new_record
  539. client = Client.new
  540. client.destroy
  541. assert client.frozen?
  542. end
  543. def test_destroy_record_with_associations
  544. client = Client.find(3)
  545. client.destroy
  546. assert client.frozen?
  547. assert_kind_of Firm, client.firm
  548. assert_raises(TypeError) { client.name = "something else" }
  549. end
  550. def test_update_attribute
  551. assert !Topic.find(1).approved?
  552. Topic.find(1).update_attribute("approved", true)
  553. assert Topic.find(1).approved?
  554. Topic.find(1).update_attribute(:approved, false)
  555. assert !Topic.find(1).approved?
  556. end
  557. def test_update_attributes
  558. topic = Topic.find(1)
  559. assert !topic.approved?
  560. assert_equal "The First Topic", topic.title
  561. topic.update_attributes("approved" => true, "title" => "The First Topic Updated")
  562. topic.reload
  563. assert topic.approved?
  564. assert_equal "The First Topic Updated", topic.title
  565. topic.update_attributes(:approved => false, :title => "The First Topic")
  566. topic.reload
  567. assert !topic.approved?
  568. assert_equal "The First Topic", topic.title
  569. end
  570. def test_update_attributes!
  571. reply = Reply.find(2)
  572. assert_equal "The Second Topic's of the day", reply.title
  573. assert_equal "Have a nice day", reply.content
  574. reply.update_attributes!("title" => "The Second Topic's of the day updated", "content" => "Have a nice evening")
  575. reply.reload
  576. assert_equal "The Second Topic's of the day updated", reply.title
  577. assert_equal "Have a nice evening", reply.content
  578. reply.update_attributes!(:title => "The Second Topic's of the day", :content => "Have a nice day")
  579. reply.reload
  580. assert_equal "The Second Topic's of the day", reply.title
  581. assert_equal "Have a nice day", reply.content
  582. assert_raise(ActiveRecord::RecordInvalid) { reply.update_attributes!(:title => nil, :content => "Have a nice evening") }
  583. end
  584. def test_mass_assignment_protection
  585. firm = Firm.new
  586. firm.attributes = { "name" => "Next Angle", "rating" => 5 }
  587. assert_equal 1, firm.rating
  588. end
  589. def test_mass_assignment_protection_against_class_attribute_writers
  590. [:logger, :configurations, :primary_key_prefix_type, :table_name_prefix, :table_name_suffix, :pluralize_table_names, :colorize_logging,
  591. :default_timezone, :allow_concurrency, :generate_read_methods, :schema_format, :verification_timeout, :lock_optimistically, :record_timestamps].each do |method|
  592. assert Task.respond_to?(method)
  593. assert Task.respond_to?("#{method}=")
  594. assert Task.new.respond_to?(method)
  595. assert !Task.new.respond_to?("#{method}=")
  596. end
  597. end
  598. def test_customized_primary_key_remains_protected
  599. subscriber = Subscriber.new(:nick => 'webster123', :name => 'nice try')
  600. assert_nil subscriber.id
  601. keyboard = Keyboard.new(:key_number => 9, :name => 'nice try')
  602. assert_nil keyboard.id
  603. end
  604. def test_customized_primary_key_remains_protected_when_refered_to_as_id
  605. subscriber = Subscriber.new(:id => 'webster123', :name => 'nice try')
  606. assert_nil subscriber.id
  607. keyboard = Keyboard.new(:id => 9, :name => 'nice try')
  608. assert_nil keyboard.id
  609. end
  610. def test_mass_assignment_protection_on_defaults
  611. firm = Firm.new
  612. firm.attributes = { "id" => 5, "type" => "Client" }
  613. assert_nil firm.id
  614. assert_equal "Firm", firm[:type]
  615. end
  616. def test_mass_assignment_accessible
  617. reply = Reply.new("title" => "hello", "content" => "world", "approved" => true)
  618. reply.save
  619. assert reply.approved?
  620. reply.approved = false
  621. reply.save
  622. assert !reply.approved?
  623. end
  624. def test_mass_assignment_protection_inheritance
  625. assert_nil LoosePerson.accessible_attributes
  626. assert_equal [ :credit_rating, :administrator ], LoosePerson.protected_attributes
  627. assert_nil LooseDescendant.accessible_attributes
  628. assert_equal [ :credit_rating, :administrator, :phone_number ], LooseDescendant.protected_attributes
  629. assert_nil TightPerson.protected_attributes
  630. assert_equal [ :name, :address ], TightPerson.accessible_attributes
  631. assert_nil TightDescendant.protected_attributes
  632. assert_equal [ :name, :address, :phone_number ], TightDescendant.accessible_attributes
  633. end
  634. def test_multiparameter_attributes_on_date
  635. attributes = { "last_read(1i)" => "2004", "last_read(2i)" => "6", "last_read(3i)" => "24" }
  636. topic = Topic.find(1)
  637. topic.attributes = attributes
  638. # note that extra #to_date call allows test to pass for Oracle, which
  639. # treats dates/times the same
  640. assert_date_from_db Date.new(2004, 6, 24), topic.last_read.to_date
  641. end
  642. def test_multiparameter_attributes_on_date_with_empty_date
  643. attributes = { "last_read(1i)" => "2004", "last_read(2i)" => "6", "last_read(3i)" => "" }
  644. topic = Topic.find(1)
  645. topic.attributes = attributes
  646. # note that extra #to_date call allows test to pass for Oracle, which
  647. # treats dates/times the same
  648. assert_date_from_db Date.new(2004, 6, 1), topic.last_read.to_date
  649. end
  650. def test_multiparameter_attributes_on_date_with_all_empty
  651. attributes = { "last_read(1i)" => "", "last_read(2i)" => "", "last_read(3i)" => "" }
  652. topic = Topic.find(1)
  653. topic.attributes = attributes
  654. assert_nil topic.last_read
  655. end
  656. def test_multiparameter_attributes_on_time
  657. attributes = {
  658. "written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
  659. "written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => "00"
  660. }
  661. topic = Topic.find(1)
  662. topic.attributes = attributes
  663. assert_equal Time.local(2004, 6, 24, 16, 24, 0), topic.written_on
  664. end
  665. def test_multiparameter_attributes_on_time_with_empty_seconds
  666. attributes = {
  667. "written_on(1i)" => "2004", "written_on(2i)" => "6", "written_on(3i)" => "24",
  668. "written_on(4i)" => "16", "written_on(5i)" => "24", "written_on(6i)" => ""
  669. }
  670. topic = Topic.find(1)
  671. topic.attributes = attributes
  672. assert_equal Time.local(2004, 6, 24, 16, 24, 0), topic.written_on
  673. end
  674. def test_multiparameter_mass_assignment_protector
  675. task = Task.new
  676. time = Time.mktime(2000, 1, 1, 1)
  677. task.starting = time
  678. attributes = { "starting(1i)" => "2004", "starting(2i)" => "6", "starting(3i)" => "24" }
  679. task.attributes = attributes
  680. assert_equal time, task.starting
  681. end
  682. def test_multiparameter_assignment_of_aggregation
  683. customer = Customer.new
  684. address = Address.new("The Street", "The City", "The Country")
  685. attributes = { "address(1)" => address.street, "address(2)" => address.city, "address(3)" => address.country }
  686. customer.attributes = attributes
  687. assert_equal address, customer.address
  688. end
  689. def test_attributes_on_dummy_time
  690. # Oracle, SQL Server, and Sybase do not have a TIME datatype.
  691. return true if current_adapter?(:SQLServerAdapter, :OracleAdapter, :SybaseAdapter)
  692. attributes = {
  693. "bonus_time" => "5:42:00AM"
  694. }
  695. topic = Topic.find(1)
  696. topic.attributes = attributes
  697. assert_equal Time.local(2000, 1, 1, 5, 42, 0), topic.bonus_time
  698. end
  699. def test_boolean
  700. b_false = Booleantest.create({ "value" => false })
  701. false_id = b_false.id
  702. b_true = Booleantest.create({ "value" => true })
  703. true_id = b_true.id
  704. b_false = Booleantest.find(false_id)
  705. assert !b_false.value?
  706. b_true = Booleantest.find(true_id)
  707. assert b_true.value?
  708. end
  709. def test_boolean_cast_from_string
  710. b_false = Booleantest.create({ "value" => "0" })
  711. false_id = b_false.id
  712. b_true = Booleantest.create({ "value" => "1" })
  713. true_id = b_true.id
  714. b_false = Booleantest.find(false_id)
  715. assert !b_false.value?
  716. b_true = Booleantest.find(true_id)
  717. assert b_true.value?
  718. end
  719. def test_clone
  720. topic = Topic.find(1)
  721. cloned_topic = nil
  722. assert_nothing_raised { cloned_topic = topic.clone }
  723. assert_equal topic.title, cloned_topic.title
  724. assert cloned_topic.new_record?
  725. # test if the attributes have been cloned
  726. topic.title = "a"
  727. cloned_topic.title = "b"
  728. assert_equal "a", topic.title
  729. assert_equal "b", cloned_topic.title
  730. # test if the attribute values have been cloned
  731. topic.title = {"a" => "b"}
  732. cloned_topic = topic.clone
  733. cloned_topic.title["a"] = "c"
  734. assert_equal "b", topic.title["a"]
  735. cloned_topic.save
  736. assert !cloned_topic.new_record?
  737. assert cloned_topic.id != topic.id
  738. end
  739. def test_clone_with_aggregate_of_same_name_as_attribute
  740. dev = DeveloperWithAggregate.find(1)
  741. assert_kind_of DeveloperSalary, dev.salary
  742. clone = nil
  743. assert_nothing_raised { clone = dev.clone }
  744. assert_kind_of DeveloperSalary, clone.salary
  745. assert_equal dev.salary.amount, clone.salary.amount
  746. assert clone.new_record?
  747. # test if the attributes have been cloned
  748. original_amount = clone.salary.amount
  749. dev.salary.amount = 1
  750. assert_equal original_amount, clone.salary.amount
  751. assert clone.save
  752. assert !clone.new_record?
  753. assert clone.id != dev.id
  754. end
  755. def test_clone_preserves_subtype
  756. clone = nil
  757. assert_nothing_raised { clone = Company.find(3).clone }
  758. assert_kind_of Client, clone
  759. end
  760. def test_bignum
  761. company = Company.find(1)
  762. company.rating = 2147483647
  763. company.save
  764. company = Company.find(1)
  765. assert_equal 2147483647, company.rating
  766. end
  767. # TODO: extend defaults tests to other databases!
  768. if current_adapter?(:PostgreSQLAdapter)
  769. def test_default
  770. default = Default.new
  771. # fixed dates / times
  772. assert_equal Date.new(2004, 1, 1), default.fixed_date
  773. assert_equal Time.local(2004, 1,1,0,0,0,0), default.fixed_time
  774. # char types
  775. assert_equal 'Y', default.char1
  776. assert_equal 'a varchar field', default.char2
  777. assert_equal 'a text field', default.char3
  778. end
  779. class Geometric < ActiveRecord::Base; end
  780. def test_geometric_content
  781. # accepted format notes:
  782. # ()'s aren't required
  783. # values can be a mix of float or integer
  784. g = Geometric.new(
  785. :a_point => '(5.0, 6.1)',
  786. #:a_line => '((2.0, 3), (5.5, 7.0))' # line type is currently unsupported in postgresql
  787. :a_line_segment => '(2.0, 3), (5.5, 7.0)',
  788. :a_box => '2.0, 3, 5.5, 7.0',
  789. :a_path => '[(2.0, 3), (5.5, 7.0), (8.5, 11.0)]', # [ ] is an open path
  790. :a_polygon => '((2.0, 3), (5.5, 7.0), (8.5, 11.0))',
  791. :a_circle => '<(5.3, 10.4), 2>'
  792. )
  793. assert g.save
  794. # Reload and check that we have all the geometric attributes.
  795. h = Geometric.find(g.id)
  796. assert_equal '(5,6.1)', h.a_point
  797. assert_equal '[(2,3),(5.5,7)]', h.a_line_segment
  798. assert_equal '(5.5,7),(2,3)', h.a_box # reordered to store upper right corner then bottom left corner
  799. assert_equal '[(2,3),(5.5,7),(8.5,11)]', h.a_path
  800. assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_polygon
  801. assert_equal '<(5.3,10.4),2>', h.a_circle
  802. # use a geometric function to test for an open path
  803. objs = Geometric.find_by_sql ["select isopen(a_path) from geometrics where id = ?", g.id]
  804. assert_equal objs[0].isopen, 't'
  805. # test alternate formats when defining the geometric types
  806. g = Geometric.new(
  807. :a_point => '5.0, 6.1',
  808. #:a_line => '((2.0, 3), (5.5, 7.0))' # line type is currently unsupported in postgresql
  809. :a_line_segment => '((2.0, 3), (5.5, 7.0))',
  810. :a_box => '(2.0, 3), (5.5, 7.0)',
  811. :a_path => '((2.0, 3), (5.5, 7.0), (8.5, 11.0))', # ( ) is a closed path
  812. :a_polygon => '2.0, 3, 5.5, 7.0, 8.5, 11.0',
  813. :a_circle => '((5.3, 10.4), 2)'
  814. )
  815. assert g.save
  816. # Reload and check that we have all the geometric attributes.
  817. h = Geometric.find(g.id)
  818. assert_equal '(5,6.1)', h.a_point
  819. assert_equal '[(2,3),(5.5,7)]', h.a_line_segment
  820. assert_equal '(5.5,7),(2,3)', h.a_box # reordered to store upper right corner then bottom left corner
  821. assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_path
  822. assert_equal '((2,3),(5.5,7),(8.5,11))', h.a_polygon
  823. assert_equal '<(5.3,10.4),2>', h.a_circle
  824. # use a geometric function to test for an closed path
  825. objs = Geometric.find_by_sql ["select isclosed(a_path) from geometrics where id = ?", g.id]
  826. assert_equal objs[0].isclosed, 't'
  827. end
  828. end
  829. class NumericData < ActiveRecord::Base
  830. self.table_name = 'numeric_data'
  831. end
  832. def test_numeric_fields
  833. m = NumericData.new(
  834. :bank_balance => 1586.43,
  835. :big_bank_balance => BigDecimal("1000234000567.95"),
  836. :world_population => 6000000000,
  837. :my_house_population => 3
  838. )
  839. assert m.save
  840. m1 = NumericData.find(m.id)
  841. assert_not_nil m1
  842. # As with migration_test.rb, we should make world_population >= 2**62
  843. # to cover 64-bit platforms and test it is a Bignum, but the main thing
  844. # is that it's an Integer.
  845. assert_kind_of Integer, m1.world_population
  846. assert_equal 6000000000, m1.world_population
  847. assert_kind_of Fixnum, m1.my_house_population
  848. assert_equal 3, m1.my_house_population
  849. assert_kind_of BigDecimal, m1.bank_balance
  850. assert_equal BigDecimal("1586.43"), m1.bank_balance
  851. assert_kind_of BigDecimal, m1.big_bank_balance
  852. assert_equal BigDecimal("1000234000567.95"), m1.big_bank_balance
  853. end
  854. def test_auto_id
  855. auto = AutoId.new
  856. auto.save
  857. assert (auto.id > 0)
  858. end
  859. def quote_column_name(name)
  860. "<#{name}>"
  861. end
  862. def test_quote_keys
  863. ar = AutoId.new
  864. source = {"foo" => "bar", "baz" => "quux"}
  865. actual = ar.send(:quote_columns, self, source)
  866. inverted = actual.invert
  867. assert_equal("<foo>", inverted["bar"])
  868. assert_equal("<baz>", inverted["quux"])
  869. end
  870. def test_sql_injection_via_find
  871. assert_raises(ActiveRecord::RecordNotFound, ActiveRecord::StatementInvalid) do
  872. Topic.find("123456 OR id > 0")
  873. end
  874. end
  875. def test_column_name_properly_quoted
  876. col_record = ColumnName.new
  877. col_record.references = 40
  878. assert col_record.save
  879. col_record.references = 41
  880. assert col_record.save
  881. assert_not_nil c2 = ColumnName.find(col_record.id)
  882. assert_equal(41, c2.references)
  883. end
  884. def test_quoting_arrays
  885. replies = Reply.find(:all, :conditions => [ "id IN (?)", topics(:first).replies.collect(&:id) ])
  886. assert_equal topics(:first).replies.size, replies.size
  887. replies = Reply.find(:all, :conditions => [ "id IN (?)", [] ])
  888. assert_equal 0, replies.size
  889. end
  890. MyObject = Struct.new :attribute1, :attribute2
  891. def test_serialized_attribute
  892. myobj = MyObject.new('value1', 'value2')
  893. topic = Topic.create("content" => myobj)
  894. Topic.serialize("content", MyObject)
  895. assert_equal(myobj, topic.content)
  896. end
  897. def test_serialized_attribute_with_class_constraint
  898. myobj = MyObject.new('value1', 'value2')
  899. topic = Topic.create("content" => myobj)
  900. Topic.serialize(:content, Hash)
  901. assert_raise(ActiveRecord::SerializationTypeMismatch) { Topic.find(topic.id).content }
  902. settings = { "color" => "blue" }
  903. Topic.find(topic.id).update_attribute("content", settings)
  904. assert_equal(settings, Topic.find(topic.id).content)
  905. Topic.serialize(:content)
  906. end
  907. def test_quote
  908. author_name = "\\ \001 ' \n \\n \""
  909. topic = Topic.create('author_name' => author_name)
  910. assert_equal author_name, Topic.find(topic.id).author_name
  911. end
  912. def test_quote_chars
  913. str = 'The Narrator'
  914. topic = Topic.create(:author_name => str)
  915. assert_equal str, topic.author_name
  916. assert_kind_of ActiveSupport::Multibyte::Chars, str.chars
  917. topic = Topic.find_by_author_name(str.chars)
  918. assert_kind_of Topic, topic
  919. assert_equal str, topic.author_name, "The right topic should have been found by name even with name passed as Chars"
  920. end
  921. def test_class_level_destroy
  922. should_be_destroyed_reply = Reply.create("title" => "hello", "content" => "world")
  923. Topic.find(1).replies << should_be_destroyed_reply
  924. Topic.destroy(1)
  925. assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1) }
  926. assert_raise(ActiveRecord::RecordNotFound) { Reply.find(should_be_destroyed_reply.id) }
  927. end
  928. def test_class_level_delete
  929. should_be_destroyed_reply = Reply.create("title" => "hello", "content" => "world")
  930. Topic.find(1).replies << should_be_destroyed_reply
  931. Topic.delete(1)
  932. assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1) }
  933. assert_nothing_raised { Reply.find(should_be_destroyed_reply.id) }
  934. end
  935. def test_increment_attribute
  936. assert_equal 1, topics(:first).replies_count
  937. topics(:first).increment! :replies_count
  938. assert_equal 2, topics(:first, :reload).replies_count
  939. topics(:first).increment(:replies_count).increment!(:replies_count)
  940. assert_equal 4, topics(:first, :reload).replies_count
  941. end
  942. def test_increment_nil_attribute
  943. assert_nil topics(:first).parent_id
  944. topics(:first).increment! :parent_id
  945. assert_equal 1, topics(:first).parent_id
  946. end
  947. def test_decrement_attribute
  948. topics(:first).increment(:replies_count).increment!(:replies_count)
  949. assert_equal 3, topics(:first).replies_count
  950. topics(:first).decrement!(:replies_count)
  951. assert_equal 2, topics(:first, :reload).replies_count
  952. topics(:first).decrement(:replies_count).decrement!(:replies_count)
  953. assert_equal 0, topics(:first, :reload).replies_count
  954. end
  955. def test_toggle_attribute
  956. assert !topics(:first).approved?
  957. topics(:first).toggle!(:approved)
  958. assert topics(:first).approved?
  959. topic = topics(:first)
  960. topic.toggle(:approved)
  961. assert !topic.approved?
  962. topic.reload
  963. assert topic.approved?
  964. end
  965. def test_reload
  966. t1 = Topic.find(1)
  967. t2 = Topic.find(1)
  968. t1.title = "something else"
  969. t1.save
  970. t2.reload
  971. assert_equal t1.title, t2.title
  972. end
  973. def test_define_attr_method_with_value
  974. k = Class.new( ActiveRecord::Base )
  975. k.send(:define_attr_method, :table_name, "foo")
  976. assert_equal "foo", k.table_name
  977. end
  978. def test_define_attr_method_with_block
  979. k = Class.new( ActiveRecord::Base )
  980. k.send(:define_attr_method, :primary_key) { "sys_" + original_primary_key }
  981. assert_equal "sys_id", k.primary_key
  982. end
  983. def test_set_table_name_with_value
  984. k = Class.new( ActiveRecord::Base )
  985. k.table_name = "foo"
  986. assert_equal "foo", k.table_name
  987. k.set_table_name "bar"
  988. assert_equal "bar", k.table_name
  989. end
  990. def test_set_table_name_with_block
  991. k = Class.new( ActiveRecord::Base )
  992. k.set_table_name { "ks" }
  993. assert_equal "ks", k.table_name
  994. end
  995. def test_set_primary_key_with_value
  996. k = Class.new( ActiveRecord::Base )
  997. k.primary_key = "foo"
  998. assert_equal "foo", k.primary_key
  999. k.set_primary_key "bar"
  1000. assert_equal "bar", k.primary_key
  1001. end
  1002. def test_set_primary_key_with_block
  1003. k = Class.new( ActiveRecord::Base )
  1004. k.set_primary_key { "sys_" + original_primary_key }
  1005. assert_equal "sys_id", k.primary_key
  1006. end
  1007. def test_set_inheritance_column_with_value
  1008. k = Class.new( ActiveRecord::Base )
  1009. k.inheritance_column = "foo"
  1010. assert_equal "foo", k.inheritance_column
  1011. k.set_inheritance_column "bar"
  1012. assert_equal "bar", k.inheritance_column
  1013. end
  1014. def test_set_inheritance_column_with_block
  1015. k = Class.new( ActiveRecord::Base )
  1016. k.set_inheritance_column { original_inheritance_column + "_id" }
  1017. assert_equal "type_id", k.inheritance_column
  1018. end
  1019. def test_count_with_join
  1020. res = Post.count_by_sql "SELECT COUNT(*) FROM posts LEFT JOIN comments ON posts.id=comments.post_id WHERE posts.#{QUOTED_TYPE} = 'Post'"
  1021. res2 = nil
  1022. assert_deprecated 'count' do
  1023. res2 = Post.count("posts.#{QUOTED_TYPE} = 'Post'",
  1024. "LEFT JOIN comments ON posts.id=comments.post_id")
  1025. end
  1026. assert_equal res, res2
  1027. res3 = nil
  1028. assert_nothing_raised do
  1029. res3 = Post.count(:conditions => "posts.#{QUOTED_TYPE} = 'Post'",
  1030. :joins => "LEFT JOIN comments ON posts.id=comments.post_id")
  1031. end
  1032. assert_equal res, res3
  1033. 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"
  1034. res5 = nil
  1035. assert_nothing_raised do
  1036. res5 = Post.count(:conditions => "p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id",
  1037. :joins => "p, comments co",
  1038. :select => "p.id")
  1039. end
  1040. assert_equal res4, res5
  1041. 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"
  1042. res7 = nil
  1043. assert_nothing_raised do
  1044. res7 = Post.count(:conditions => "p.#{QUOTED_TYPE} = 'Post' AND p.id=co.post_id",
  1045. :joins => "p, comments co",
  1046. :select => "p.id",
  1047. :distinct => true)
  1048. end
  1049. assert_equal res6, res7
  1050. end
  1051. def test_clear_association_cache_stored
  1052. firm = Firm.find(1)
  1053. assert_kind_of Firm, firm
  1054. firm.clear_association_cache
  1055. assert_equal Firm.find(1).clients.collect{ |x| x.name }.sort, firm.clients.collect{ |x| x.name }.sort
  1056. end
  1057. def test_clear_association_cache_new_record
  1058. firm = Firm.new
  1059. client_stored = Client.find(3)
  1060. client_new = Client.new
  1061. client_new.name = "The Joneses"
  1062. clients = [ client_stored, client_new ]
  1063. firm.clients << clients
  1064. firm.clear_association_cache
  1065. assert_equal firm.clients.collect{ |x| x.name }.sort, clients.collect{ |x| x.name }.sort
  1066. end
  1067. def test_interpolate_sql
  1068. assert_nothing_raised { Category.new.send(:interpolate_sql, 'foo@bar') }
  1069. assert_nothing_raised { Category.new.send(:interpolate_sql, 'foo bar) baz') }
  1070. assert_nothing_raised { Category.new.send(:interpolate_sql, 'foo bar} baz') }
  1071. end
  1072. def test_scoped_find_conditions
  1073. scoped_developers = Developer.with_scope(:find => { :conditions => 'salary > 90000' }) do
  1074. Developer.find(:all, :conditions => 'id < 5')
  1075. end
  1076. assert !scoped_developers.include?(developers(:david)) # David's salary is less than 90,000
  1077. assert_equal 3, scoped_developers.size
  1078. end
  1079. def test_scoped_find_limit_offset
  1080. scoped_developers = Developer.with_scope(:find => { :limit => 3, :offset => 2 }) do
  1081. Developer.find(:all, :order => 'id')
  1082. end
  1083. assert !scoped_developers.include?(developers(:david))
  1084. assert !scoped_developers.include?(developers(:jamis))
  1085. assert_equal 3, scoped_developers.size
  1086. # Test without scoped find conditions to ensure we get the whole thing
  1087. developers = Developer.find(:all, :order => 'id')
  1088. assert_equal Developer.count, developers.size
  1089. end
  1090. def test_scoped_find_order
  1091. # Test order in scope
  1092. scoped_developers = Developer.with_scope(:find => { :limit => 1, :order => 'salary DESC' }) do
  1093. Developer.find(:all)
  1094. end
  1095. assert_equal 'Jamis', scoped_developers.first.name
  1096. assert scoped_developers.include?(developers(:jamis))
  1097. # Test scope without order and order in find
  1098. scoped_developers = Developer.with_scope(:find => { :limit => 1 }) do
  1099. Developer.find(:all, :order => 'salary DESC')
  1100. end
  1101. # Test scope order + find order, find has priority
  1102. scoped_developers = Developer.with_scope(:find => { :limit => 3, :order => 'id DESC' }) do
  1103. Developer.find(:all, :order => 'salary ASC')
  1104. end
  1105. assert scoped_developers.include?(developers(:poor_jamis))
  1106. assert scoped_developers.include?(developers(:david))
  1107. assert scoped_developers.include?(developers(:dev_10))
  1108. # Test without scoped find conditions to ensure we get the right thing
  1109. developers = Developer.find(:all, :order => 'id', :limit => 1)
  1110. assert scoped_developers.include?(developers(:david))
  1111. end
  1112. def test_scoped_find_limit_offset_including_has_many_association
  1113. topics = Topic.with_scope(:find => {:limit => 1, :offset => 1, :include => :replies}) do
  1114. Topic.find(:all, :order => "topics.id")
  1115. end
  1116. assert_equal 1, topics.size
  1117. assert_equal 2, topics.first.id
  1118. end
  1119. def test_scoped_find_order_including_has_many_association
  1120. developers = Developer.with_scope(:find => { :order => 'developers.salary DESC', :include => :projects }) do
  1121. Developer.find(:all)
  1122. end
  1123. assert developers.size >= 2
  1124. for i in 1...developers.size
  1125. assert developers[i-1].salary >= developers[i].salary
  1126. end
  1127. end
  1128. def test_abstract_class
  1129. assert !ActiveRecord::Base.abstract_class?
  1130. assert LoosePerson.abstract_class?
  1131. assert !LooseDescendant.abstract_class?
  1132. end
  1133. def test_base_class
  1134. assert_equal LoosePerson, LoosePerson.base_class
  1135. assert_equal LooseDescendant, LooseDescendant.base_class
  1136. assert_equal TightPerson, TightPerson.base_class
  1137. assert_equal TightPerson, TightDescendant.base_class
  1138. assert_equal Post, Post.base_class
  1139. assert_equal Post, SpecialPost.base_class
  1140. assert_equal Post, StiPost.base_class
  1141. assert_equal SubStiPost, SubStiPost.base_class
  1142. end
  1143. def test_descends_from_active_record
  1144. # Tries to call Object.abstract_class?
  1145. assert_raise(NoMethodError) do
  1146. ActiveRecord::Base.descends_from_active_record?
  1147. end
  1148. # Abstract subclass of AR::Base.
  1149. assert LoosePerson.descends_from_active_record?
  1150. # Concrete subclass of an abstract class.
  1151. assert LooseDescendant.descends_from_active_record?
  1152. # Concrete subclass of AR::Base.
  1153. assert TightPerson.descends_from_active_record?
  1154. # Concrete subclass of a concrete class but has no type column.
  1155. assert TightDescendant.descends_from_active_record?
  1156. # Concrete subclass of AR::Base.
  1157. assert Post.descends_from_active_record?
  1158. # Abstract subclass of a concrete class which has a type column.
  1159. # This is pathological, as you'll never have Sub < Abstract < Concrete.
  1160. assert !StiPost.descends_from_active_record?
  1161. # Concrete subclasses an abstract class which has a type column.
  1162. assert !SubStiPost.descends_from_active_record?
  1163. end
  1164. def test_find_on_abstract_base_class_doesnt_use_type_condition
  1165. old_class = LooseDescendant
  1166. Object.send :remove_const, :LooseDescendant
  1167. descendant = old_class.create!
  1168. assert_not_nil LoosePerson.find(descendant.id), "Should have found instance of LooseDescendant when finding abstract LoosePerson: #{descendant.inspect}"
  1169. ensure
  1170. unless Object.const_defined?(:LooseDescendant)
  1171. Object.const_set :LooseDescendant, old_class
  1172. end
  1173. end
  1174. def test_assert_queries
  1175. query = lambda { ActiveRecord::Base.connection.execute 'select count(*) from developers' }
  1176. assert_queries(2) { 2.times { query.call } }
  1177. assert_queries 1, &query
  1178. assert_no_queries { assert true }
  1179. end
  1180. def test_to_xml
  1181. xml = topics(:first).to_xml(:indent => 0, :skip_instruct => true)
  1182. bonus_time_in_current_timezone = topics(:first).bonus_time.xmlschema
  1183. written_on_in_current_timezone = topics(:first).written_on.xmlschema
  1184. last_read_in_current_timezone = topics(:first).last_read.xmlschema
  1185. assert_equal "<topic>", xml.first(7)
  1186. assert xml.include?(%(<title>The First Topic</title>))
  1187. assert xml.include?(%(<author-name>David</author-name>))
  1188. assert xml.include?(%(<id type="integer">1</id>))
  1189. assert xml.include?(%(<replies-count type="integer">1</replies-count>))
  1190. assert xml.include?(%(<written-on type="datetime">#{written_on_in_current_timezone}</written-on>))
  1191. assert xml.include?(%(<content>Have a nice day</content>))
  1192. assert xml.include?(%(<author-email-address>david@loudthinking.com</author-email-address>))
  1193. assert xml.match(%(<parent-id type="integer"></parent-id>))
  1194. if current_adapter?(:SybaseAdapter, :SQLServerAdapter, :OracleAdapter)
  1195. assert xml.include?(%(<last-read type="datetime">#{last_read_in_current_timezone}</last-read>))
  1196. else
  1197. assert xml.include?(%(<last-read type="date">2004-04-15</last-read>))
  1198. end
  1199. # Oracle and DB2 don't have true boolean or time-only fields
  1200. unless current_adapter?(:OracleAdapter, :DB2Adapter)
  1201. assert xml.include?(%(<approved type="boolean">false</approved>)), "Approved should be a boolean"
  1202. assert xml.include?(%(<bonus-time type="datetime">#{bonus_time_in_current_timezone}</bonus-time>))
  1203. end
  1204. end
  1205. def test_to_xml_skipping_attributes
  1206. xml = topics(:first).to_xml(:indent => 0, :skip_instruct => true, :except => [:title, :replies_count])
  1207. assert_equal "<topic>", xml.first(7)
  1208. assert !xml.include?(%(<title>The First Topic</title>))
  1209. assert xml.include?(%(<author-name>David</author-name>))
  1210. xml = topics(:first).to_xml(:indent => 0, :skip_instruct => true, :except => [:title, :author_name, :replies_count])
  1211. assert !xml.include?(%(<title>The First Topic</title>))
  1212. assert !xml.include?(%(<author-name>David</author-name>))
  1213. end
  1214. def test_to_xml_including_has_many_association
  1215. xml = topics(:first).to_xml(:indent => 0, :skip_instruct => true, :include => :replies, :except => :replies_count)
  1216. assert_equal "<topic>", xml.first(7)
  1217. assert xml.include?(%(<replies><reply>))
  1218. assert xml.include?(%(<title>The Second Topic's of the day</title>))
  1219. end
  1220. def test_array_to_xml_including_has_many_association
  1221. xml = [ topics(:first), topics(:second) ].to_xml(:indent => 0, :skip_instruct => true, :include => :replies)
  1222. assert xml.include?(%(<replies><reply>))
  1223. end
  1224. def test_array_to_xml_including_methods
  1225. xml = [ topics(:first), topics(:second) ].to_xml(:indent => 0, :skip_instruct => true, :methods => [ :topic_id ])
  1226. assert xml.include?(%(<topic-id type="integer">#{topics(:first).topic_id}</topic-id>)), xml
  1227. assert xml.include?(%(<topic-id type="integer">#{topics(:second).topic_id}</topic-id>)), xml
  1228. end
  1229. def test_array_to_xml_including_has_one_association
  1230. xml = [ companies(:firs

Large files files are truncated, but you can click here to view the full file