Updated README.rdoc again
[feedcatcher.git] / vendor / rails / activerecord / test / cases / finder_test.rb
1 require "cases/helper"
2 require 'models/author'
3 require 'models/categorization'
4 require 'models/comment'
5 require 'models/company'
6 require 'models/topic'
7 require 'models/reply'
8 require 'models/entrant'
9 require 'models/developer'
10 require 'models/post'
11 require 'models/customer'
12 require 'models/job'
13 require 'models/categorization'
14
15 class DynamicFinderMatchTest < ActiveRecord::TestCase
16 def test_find_no_match
17 assert_nil ActiveRecord::DynamicFinderMatch.match("not_a_finder")
18 end
19
20 def test_find_by
21 match = ActiveRecord::DynamicFinderMatch.match("find_by_age_and_sex_and_location")
22 assert_not_nil match
23 assert match.finder?
24 assert_equal :first, match.finder
25 assert_equal %w(age sex location), match.attribute_names
26 end
27
28 def find_by_bang
29 match = ActiveRecord::DynamicFinderMatch.match("find_by_age_and_sex_and_location!")
30 assert_not_nil match
31 assert match.finder?
32 assert match.bang?
33 assert_equal :first, match.finder
34 assert_equal %w(age sex location), match.attribute_names
35 end
36
37 def test_find_all_by
38 match = ActiveRecord::DynamicFinderMatch.match("find_all_by_age_and_sex_and_location")
39 assert_not_nil match
40 assert match.finder?
41 assert_equal :all, match.finder
42 assert_equal %w(age sex location), match.attribute_names
43 end
44
45 def test_find_or_initialize_by
46 match = ActiveRecord::DynamicFinderMatch.match("find_or_initialize_by_age_and_sex_and_location")
47 assert_not_nil match
48 assert !match.finder?
49 assert match.instantiator?
50 assert_equal :first, match.finder
51 assert_equal :new, match.instantiator
52 assert_equal %w(age sex location), match.attribute_names
53 end
54
55 def test_find_or_create_by
56 match = ActiveRecord::DynamicFinderMatch.match("find_or_create_by_age_and_sex_and_location")
57 assert_not_nil match
58 assert !match.finder?
59 assert match.instantiator?
60 assert_equal :first, match.finder
61 assert_equal :create, match.instantiator
62 assert_equal %w(age sex location), match.attribute_names
63 end
64 end
65
66 class FinderTest < ActiveRecord::TestCase
67 fixtures :companies, :topics, :entrants, :developers, :developers_projects, :posts, :comments, :accounts, :authors, :customers
68
69 def test_find
70 assert_equal(topics(:first).title, Topic.find(1).title)
71 end
72
73 # find should handle strings that come from URLs
74 # (example: Category.find(params[:id]))
75 def test_find_with_string
76 assert_equal(Topic.find(1).title,Topic.find("1").title)
77 end
78
79 def test_exists
80 assert Topic.exists?(1)
81 assert Topic.exists?("1")
82 assert Topic.exists?(:author_name => "David")
83 assert Topic.exists?(:author_name => "Mary", :approved => true)
84 assert Topic.exists?(["parent_id = ?", 1])
85 assert !Topic.exists?(45)
86
87 begin
88 assert !Topic.exists?("foo")
89 rescue ActiveRecord::StatementInvalid
90 # PostgreSQL complains about string comparison with integer field
91 rescue Exception
92 flunk
93 end
94
95 assert_raise(NoMethodError) { Topic.exists?([1,2]) }
96 end
97
98 def test_exists_returns_true_with_one_record_and_no_args
99 assert Topic.exists?
100 end
101
102 def test_does_not_exist_with_empty_table_and_no_args_given
103 Topic.delete_all
104 assert !Topic.exists?
105 end
106
107 def test_exists_with_aggregate_having_three_mappings
108 existing_address = customers(:david).address
109 assert Customer.exists?(:address => existing_address)
110 end
111
112 def test_exists_with_aggregate_having_three_mappings_with_one_difference
113 existing_address = customers(:david).address
114 assert !Customer.exists?(:address =>
115 Address.new(existing_address.street, existing_address.city, existing_address.country + "1"))
116 assert !Customer.exists?(:address =>
117 Address.new(existing_address.street, existing_address.city + "1", existing_address.country))
118 assert !Customer.exists?(:address =>
119 Address.new(existing_address.street + "1", existing_address.city, existing_address.country))
120 end
121
122 def test_find_by_array_of_one_id
123 assert_kind_of(Array, Topic.find([ 1 ]))
124 assert_equal(1, Topic.find([ 1 ]).length)
125 end
126
127 def test_find_by_ids
128 assert_equal 2, Topic.find(1, 2).size
129 assert_equal topics(:second).title, Topic.find([2]).first.title
130 end
131
132 def test_find_by_ids_with_limit_and_offset
133 assert_equal 2, Entrant.find([1,3,2], :limit => 2).size
134 assert_equal 1, Entrant.find([1,3,2], :limit => 3, :offset => 2).size
135
136 # Also test an edge case: If you have 11 results, and you set a
137 # limit of 3 and offset of 9, then you should find that there
138 # will be only 2 results, regardless of the limit.
139 devs = Developer.find :all
140 last_devs = Developer.find devs.map(&:id), :limit => 3, :offset => 9
141 assert_equal 2, last_devs.size
142 end
143
144 def test_find_an_empty_array
145 assert_equal [], Topic.find([])
146 end
147
148 def test_find_by_ids_missing_one
149 assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, 2, 45) }
150 end
151
152 def test_find_all_with_limit
153 entrants = Entrant.find(:all, :order => "id ASC", :limit => 2)
154
155 assert_equal(2, entrants.size)
156 assert_equal(entrants(:first).name, entrants.first.name)
157 end
158
159 def test_find_all_with_prepared_limit_and_offset
160 entrants = Entrant.find(:all, :order => "id ASC", :limit => 2, :offset => 1)
161
162 assert_equal(2, entrants.size)
163 assert_equal(entrants(:second).name, entrants.first.name)
164
165 entrants = Entrant.find(:all, :order => "id ASC", :limit => 2, :offset => 2)
166 assert_equal(1, entrants.size)
167 assert_equal(entrants(:third).name, entrants.first.name)
168 end
169
170 def test_find_all_with_limit_and_offset_and_multiple_orderings
171 developers = Developer.find(:all, :order => "salary ASC, id DESC", :limit => 3, :offset => 1)
172 assert_equal ["David", "fixture_10", "fixture_9"], developers.collect {|d| d.name}
173 end
174
175 def test_find_with_limit_and_condition
176 developers = Developer.find(:all, :order => "id DESC", :conditions => "salary = 100000", :limit => 3, :offset =>7)
177 assert_equal(1, developers.size)
178 assert_equal("fixture_3", developers.first.name)
179 end
180
181 def test_find_with_group
182 developers = Developer.find(:all, :group => "salary", :select => "salary")
183 assert_equal 4, developers.size
184 assert_equal 4, developers.map(&:salary).uniq.size
185 end
186
187 def test_find_with_group_and_having
188 developers = Developer.find(:all, :group => "salary", :having => "sum(salary) > 10000", :select => "salary")
189 assert_equal 3, developers.size
190 assert_equal 3, developers.map(&:salary).uniq.size
191 assert developers.all? { |developer| developer.salary > 10000 }
192 end
193
194 def test_find_with_group_and_sanitized_having
195 developers = Developer.find(:all, :group => "salary", :having => ["sum(salary) > ?", 10000], :select => "salary")
196 assert_equal 3, developers.size
197 assert_equal 3, developers.map(&:salary).uniq.size
198 assert developers.all? { |developer| developer.salary > 10000 }
199 end
200
201 def test_find_with_entire_select_statement
202 topics = Topic.find_by_sql "SELECT * FROM topics WHERE author_name = 'Mary'"
203
204 assert_equal(1, topics.size)
205 assert_equal(topics(:second).title, topics.first.title)
206 end
207
208 def test_find_with_prepared_select_statement
209 topics = Topic.find_by_sql ["SELECT * FROM topics WHERE author_name = ?", "Mary"]
210
211 assert_equal(1, topics.size)
212 assert_equal(topics(:second).title, topics.first.title)
213 end
214
215 def test_find_by_sql_with_sti_on_joined_table
216 accounts = Account.find_by_sql("SELECT * FROM accounts INNER JOIN companies ON companies.id = accounts.firm_id")
217 assert_equal [Account], accounts.collect(&:class).uniq
218 end
219
220 def test_find_first
221 first = Topic.find(:first, :conditions => "title = 'The First Topic'")
222 assert_equal(topics(:first).title, first.title)
223 end
224
225 def test_find_first_failing
226 first = Topic.find(:first, :conditions => "title = 'The First Topic!'")
227 assert_nil(first)
228 end
229
230 def test_first
231 assert_equal topics(:second).title, Topic.first(:conditions => "title = 'The Second Topic of the day'").title
232 end
233
234 def test_first_failing
235 assert_nil Topic.first(:conditions => "title = 'The Second Topic of the day!'")
236 end
237
238 def test_unexisting_record_exception_handling
239 assert_raise(ActiveRecord::RecordNotFound) {
240 Topic.find(1).parent
241 }
242
243 Topic.find(2).topic
244 end
245
246 def test_find_only_some_columns
247 topic = Topic.find(1, :select => "author_name")
248 assert_raise(ActiveRecord::MissingAttributeError) {topic.title}
249 assert_equal "David", topic.author_name
250 assert !topic.attribute_present?("title")
251 #assert !topic.respond_to?("title")
252 assert topic.attribute_present?("author_name")
253 assert topic.respond_to?("author_name")
254 end
255
256 def test_find_on_blank_conditions
257 [nil, " ", [], {}].each do |blank|
258 assert_nothing_raised { Topic.find(:first, :conditions => blank) }
259 end
260 end
261
262 def test_find_on_blank_bind_conditions
263 [ [""], ["",{}] ].each do |blank|
264 assert_nothing_raised { Topic.find(:first, :conditions => blank) }
265 end
266 end
267
268 def test_find_on_array_conditions
269 assert Topic.find(1, :conditions => ["approved = ?", false])
270 assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => ["approved = ?", true]) }
271 end
272
273 def test_find_on_hash_conditions
274 assert Topic.find(1, :conditions => { :approved => false })
275 assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :approved => true }) }
276 end
277
278 def test_find_on_hash_conditions_with_explicit_table_name
279 assert Topic.find(1, :conditions => { 'topics.approved' => false })
280 assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { 'topics.approved' => true }) }
281 end
282
283 def test_find_on_hash_conditions_with_hashed_table_name
284 assert Topic.find(1, :conditions => {:topics => { :approved => false }})
285 assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => {:topics => { :approved => true }}) }
286 end
287
288 def test_find_with_hash_conditions_on_joined_table
289 firms = Firm.all :joins => :account, :conditions => {:accounts => { :credit_limit => 50 }}
290 assert_equal 1, firms.size
291 assert_equal companies(:first_firm), firms.first
292 end
293
294 def test_find_with_hash_conditions_on_joined_table_and_with_range
295 firms = DependentFirm.all :joins => :account, :conditions => {:name => 'RailsCore', :accounts => { :credit_limit => 55..60 }}
296 assert_equal 1, firms.size
297 assert_equal companies(:rails_core), firms.first
298 end
299
300 def test_find_on_hash_conditions_with_explicit_table_name_and_aggregate
301 david = customers(:david)
302 assert Customer.find(david.id, :conditions => { 'customers.name' => david.name, :address => david.address })
303 assert_raise(ActiveRecord::RecordNotFound) {
304 Customer.find(david.id, :conditions => { 'customers.name' => david.name + "1", :address => david.address })
305 }
306 end
307
308 def test_find_on_association_proxy_conditions
309 assert_equal [1, 2, 3, 5, 6, 7, 8, 9, 10], Comment.find_all_by_post_id(authors(:david).posts).map(&:id).sort
310 end
311
312 def test_find_on_hash_conditions_with_range
313 assert_equal [1,2], Topic.find(:all, :conditions => { :id => 1..2 }).map(&:id).sort
314 assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :id => 2..3 }) }
315 end
316
317 def test_find_on_hash_conditions_with_end_exclusive_range
318 assert_equal [1,2,3], Topic.find(:all, :conditions => { :id => 1..3 }).map(&:id).sort
319 assert_equal [1,2], Topic.find(:all, :conditions => { :id => 1...3 }).map(&:id).sort
320 assert_raise(ActiveRecord::RecordNotFound) { Topic.find(3, :conditions => { :id => 2...3 }) }
321 end
322
323 def test_find_on_hash_conditions_with_multiple_ranges
324 assert_equal [1,2,3], Comment.find(:all, :conditions => { :id => 1..3, :post_id => 1..2 }).map(&:id).sort
325 assert_equal [1], Comment.find(:all, :conditions => { :id => 1..1, :post_id => 1..10 }).map(&:id).sort
326 end
327
328 def test_find_on_multiple_hash_conditions
329 assert Topic.find(1, :conditions => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => false })
330 assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }) }
331 assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :author_name => "David", :title => "HHC", :replies_count => 1, :approved => false }) }
332 assert_raise(ActiveRecord::RecordNotFound) { Topic.find(1, :conditions => { :author_name => "David", :title => "The First Topic", :replies_count => 1, :approved => true }) }
333 end
334
335 def test_condition_interpolation
336 assert_kind_of Firm, Company.find(:first, :conditions => ["name = '%s'", "37signals"])
337 assert_nil Company.find(:first, :conditions => ["name = '%s'", "37signals!"])
338 assert_nil Company.find(:first, :conditions => ["name = '%s'", "37signals!' OR 1=1"])
339 assert_kind_of Time, Topic.find(:first, :conditions => ["id = %d", 1]).written_on
340 end
341
342 def test_condition_array_interpolation
343 assert_kind_of Firm, Company.find(:first, :conditions => ["name = '%s'", "37signals"])
344 assert_nil Company.find(:first, :conditions => ["name = '%s'", "37signals!"])
345 assert_nil Company.find(:first, :conditions => ["name = '%s'", "37signals!' OR 1=1"])
346 assert_kind_of Time, Topic.find(:first, :conditions => ["id = %d", 1]).written_on
347 end
348
349 def test_condition_hash_interpolation
350 assert_kind_of Firm, Company.find(:first, :conditions => { :name => "37signals"})
351 assert_nil Company.find(:first, :conditions => { :name => "37signals!"})
352 assert_kind_of Time, Topic.find(:first, :conditions => {:id => 1}).written_on
353 end
354
355 def test_hash_condition_find_malformed
356 assert_raise(ActiveRecord::StatementInvalid) {
357 Company.find(:first, :conditions => { :id => 2, :dhh => true })
358 }
359 end
360
361 def test_hash_condition_find_with_escaped_characters
362 Company.create("name" => "Ain't noth'n like' \#stuff")
363 assert Company.find(:first, :conditions => { :name => "Ain't noth'n like' \#stuff" })
364 end
365
366 def test_hash_condition_find_with_array
367 p1, p2 = Post.find(:all, :limit => 2, :order => 'id asc')
368 assert_equal [p1, p2], Post.find(:all, :conditions => { :id => [p1, p2] }, :order => 'id asc')
369 assert_equal [p1, p2], Post.find(:all, :conditions => { :id => [p1, p2.id] }, :order => 'id asc')
370 end
371
372 def test_hash_condition_find_with_nil
373 topic = Topic.find(:first, :conditions => { :last_read => nil } )
374 assert_not_nil topic
375 assert_nil topic.last_read
376 end
377
378 def test_hash_condition_find_with_aggregate_having_one_mapping
379 balance = customers(:david).balance
380 assert_kind_of Money, balance
381 found_customer = Customer.find(:first, :conditions => {:balance => balance})
382 assert_equal customers(:david), found_customer
383 end
384
385 def test_hash_condition_find_with_aggregate_attribute_having_same_name_as_field_and_key_value_being_aggregate
386 gps_location = customers(:david).gps_location
387 assert_kind_of GpsLocation, gps_location
388 found_customer = Customer.find(:first, :conditions => {:gps_location => gps_location})
389 assert_equal customers(:david), found_customer
390 end
391
392 def test_hash_condition_find_with_aggregate_having_one_mapping_and_key_value_being_attribute_value
393 balance = customers(:david).balance
394 assert_kind_of Money, balance
395 found_customer = Customer.find(:first, :conditions => {:balance => balance.amount})
396 assert_equal customers(:david), found_customer
397 end
398
399 def test_hash_condition_find_with_aggregate_attribute_having_same_name_as_field_and_key_value_being_attribute_value
400 gps_location = customers(:david).gps_location
401 assert_kind_of GpsLocation, gps_location
402 found_customer = Customer.find(:first, :conditions => {:gps_location => gps_location.gps_location})
403 assert_equal customers(:david), found_customer
404 end
405
406 def test_hash_condition_find_with_aggregate_having_three_mappings
407 address = customers(:david).address
408 assert_kind_of Address, address
409 found_customer = Customer.find(:first, :conditions => {:address => address})
410 assert_equal customers(:david), found_customer
411 end
412
413 def test_hash_condition_find_with_one_condition_being_aggregate_and_another_not
414 address = customers(:david).address
415 assert_kind_of Address, address
416 found_customer = Customer.find(:first, :conditions => {:address => address, :name => customers(:david).name})
417 assert_equal customers(:david), found_customer
418 end
419
420 def test_bind_variables
421 assert_kind_of Firm, Company.find(:first, :conditions => ["name = ?", "37signals"])
422 assert_nil Company.find(:first, :conditions => ["name = ?", "37signals!"])
423 assert_nil Company.find(:first, :conditions => ["name = ?", "37signals!' OR 1=1"])
424 assert_kind_of Time, Topic.find(:first, :conditions => ["id = ?", 1]).written_on
425 assert_raise(ActiveRecord::PreparedStatementInvalid) {
426 Company.find(:first, :conditions => ["id=? AND name = ?", 2])
427 }
428 assert_raise(ActiveRecord::PreparedStatementInvalid) {
429 Company.find(:first, :conditions => ["id=?", 2, 3, 4])
430 }
431 end
432
433 def test_bind_variables_with_quotes
434 Company.create("name" => "37signals' go'es agains")
435 assert Company.find(:first, :conditions => ["name = ?", "37signals' go'es agains"])
436 end
437
438 def test_named_bind_variables_with_quotes
439 Company.create("name" => "37signals' go'es agains")
440 assert Company.find(:first, :conditions => ["name = :name", {:name => "37signals' go'es agains"}])
441 end
442
443 def test_bind_arity
444 assert_nothing_raised { bind '' }
445 assert_raise(ActiveRecord::PreparedStatementInvalid) { bind '', 1 }
446
447 assert_raise(ActiveRecord::PreparedStatementInvalid) { bind '?' }
448 assert_nothing_raised { bind '?', 1 }
449 assert_raise(ActiveRecord::PreparedStatementInvalid) { bind '?', 1, 1 }
450 end
451
452 def test_named_bind_variables
453 assert_equal '1', bind(':a', :a => 1) # ' ruby-mode
454 assert_equal '1 1', bind(':a :a', :a => 1) # ' ruby-mode
455
456 assert_nothing_raised { bind("'+00:00'", :foo => "bar") }
457
458 assert_kind_of Firm, Company.find(:first, :conditions => ["name = :name", { :name => "37signals" }])
459 assert_nil Company.find(:first, :conditions => ["name = :name", { :name => "37signals!" }])
460 assert_nil Company.find(:first, :conditions => ["name = :name", { :name => "37signals!' OR 1=1" }])
461 assert_kind_of Time, Topic.find(:first, :conditions => ["id = :id", { :id => 1 }]).written_on
462 end
463
464 def test_bind_enumerable
465 quoted_abc = %(#{ActiveRecord::Base.connection.quote('a')},#{ActiveRecord::Base.connection.quote('b')},#{ActiveRecord::Base.connection.quote('c')})
466
467 assert_equal '1,2,3', bind('?', [1, 2, 3])
468 assert_equal quoted_abc, bind('?', %w(a b c))
469
470 assert_equal '1,2,3', bind(':a', :a => [1, 2, 3])
471 assert_equal quoted_abc, bind(':a', :a => %w(a b c)) # '
472
473 require 'set'
474 assert_equal '1,2,3', bind('?', Set.new([1, 2, 3]))
475 assert_equal quoted_abc, bind('?', Set.new(%w(a b c)))
476
477 assert_equal '1,2,3', bind(':a', :a => Set.new([1, 2, 3]))
478 assert_equal quoted_abc, bind(':a', :a => Set.new(%w(a b c))) # '
479 end
480
481 def test_bind_empty_enumerable
482 quoted_nil = ActiveRecord::Base.connection.quote(nil)
483 assert_equal quoted_nil, bind('?', [])
484 assert_equal " in (#{quoted_nil})", bind(' in (?)', [])
485 assert_equal "foo in (#{quoted_nil})", bind('foo in (?)', [])
486 end
487
488 def test_bind_string
489 assert_equal ActiveRecord::Base.connection.quote(''), bind('?', '')
490 end
491
492 def test_bind_chars
493 quoted_bambi = ActiveRecord::Base.connection.quote("Bambi")
494 quoted_bambi_and_thumper = ActiveRecord::Base.connection.quote("Bambi\nand\nThumper")
495 assert_equal "name=#{quoted_bambi}", bind('name=?', "Bambi")
496 assert_equal "name=#{quoted_bambi_and_thumper}", bind('name=?', "Bambi\nand\nThumper")
497 assert_equal "name=#{quoted_bambi}", bind('name=?', "Bambi".mb_chars)
498 assert_equal "name=#{quoted_bambi_and_thumper}", bind('name=?', "Bambi\nand\nThumper".mb_chars)
499 end
500
501 def test_bind_record
502 o = Struct.new(:quoted_id).new(1)
503 assert_equal '1', bind('?', o)
504
505 os = [o] * 3
506 assert_equal '1,1,1', bind('?', os)
507 end
508
509 def test_named_bind_with_postgresql_type_casts
510 l = Proc.new { bind(":a::integer '2009-01-01'::date", :a => '10') }
511 assert_nothing_raised(&l)
512 assert_equal "#{ActiveRecord::Base.quote_value('10')}::integer '2009-01-01'::date", l.call
513 end
514
515 def test_string_sanitation
516 assert_not_equal "#{ActiveRecord::Base.connection.quoted_string_prefix}'something ' 1=1'", ActiveRecord::Base.sanitize("something ' 1=1")
517 assert_equal "#{ActiveRecord::Base.connection.quoted_string_prefix}'something; select table'", ActiveRecord::Base.sanitize("something; select table")
518 end
519
520 def test_count
521 assert_equal(0, Entrant.count(:conditions => "id > 3"))
522 assert_equal(1, Entrant.count(:conditions => ["id > ?", 2]))
523 assert_equal(2, Entrant.count(:conditions => ["id > ?", 1]))
524 end
525
526 def test_count_by_sql
527 assert_equal(0, Entrant.count_by_sql("SELECT COUNT(*) FROM entrants WHERE id > 3"))
528 assert_equal(1, Entrant.count_by_sql(["SELECT COUNT(*) FROM entrants WHERE id > ?", 2]))
529 assert_equal(2, Entrant.count_by_sql(["SELECT COUNT(*) FROM entrants WHERE id > ?", 1]))
530 end
531
532 def test_dynamic_finders_should_go_through_the_find_class_method
533 Topic.expects(:find).with(:first, :conditions => { :title => 'The First Topic!' })
534 Topic.find_by_title("The First Topic!")
535
536 Topic.expects(:find).with(:last, :conditions => { :title => 'The Last Topic!' })
537 Topic.find_last_by_title("The Last Topic!")
538
539 Topic.expects(:find).with(:all, :conditions => { :title => 'A Topic.' })
540 Topic.find_all_by_title("A Topic.")
541
542 Topic.expects(:find).with(:first, :conditions => { :title => 'Does not exist yet for sure!' }).times(2)
543 Topic.find_or_initialize_by_title('Does not exist yet for sure!')
544 Topic.find_or_create_by_title('Does not exist yet for sure!')
545 end
546
547 def test_find_by_one_attribute
548 assert_equal topics(:first), Topic.find_by_title("The First Topic")
549 assert_nil Topic.find_by_title("The First Topic!")
550 end
551
552 def test_find_by_one_attribute_bang
553 assert_equal topics(:first), Topic.find_by_title!("The First Topic")
554 assert_raise(ActiveRecord::RecordNotFound) { Topic.find_by_title!("The First Topic!") }
555 end
556
557 def test_find_by_one_attribute_caches_dynamic_finder
558 # ensure this test can run independently of order
559 class << Topic; self; end.send(:remove_method, :find_by_title) if Topic.public_methods.any? { |m| m.to_s == 'find_by_title' }
560 assert !Topic.public_methods.any? { |m| m.to_s == 'find_by_title' }
561 t = Topic.find_by_title("The First Topic")
562 assert Topic.public_methods.any? { |m| m.to_s == 'find_by_title' }
563 end
564
565 def test_dynamic_finder_returns_same_results_after_caching
566 # ensure this test can run independently of order
567 class << Topic; self; end.send(:remove_method, :find_by_title) if Topic.public_method_defined?(:find_by_title)
568 t = Topic.find_by_title("The First Topic")
569 assert_equal t, Topic.find_by_title("The First Topic") # find_by_title has been cached
570 end
571
572 def test_find_by_one_attribute_with_order_option
573 assert_equal accounts(:signals37), Account.find_by_credit_limit(50, :order => 'id')
574 assert_equal accounts(:rails_core_account), Account.find_by_credit_limit(50, :order => 'id DESC')
575 end
576
577 def test_find_by_one_attribute_with_conditions
578 assert_equal accounts(:rails_core_account), Account.find_by_credit_limit(50, :conditions => ['firm_id = ?', 6])
579 end
580
581 def test_find_by_one_attribute_that_is_an_aggregate
582 address = customers(:david).address
583 assert_kind_of Address, address
584 found_customer = Customer.find_by_address(address)
585 assert_equal customers(:david), found_customer
586 end
587
588 def test_find_by_one_attribute_that_is_an_aggregate_with_one_attribute_difference
589 address = customers(:david).address
590 assert_kind_of Address, address
591 missing_address = Address.new(address.street, address.city, address.country + "1")
592 assert_nil Customer.find_by_address(missing_address)
593 missing_address = Address.new(address.street, address.city + "1", address.country)
594 assert_nil Customer.find_by_address(missing_address)
595 missing_address = Address.new(address.street + "1", address.city, address.country)
596 assert_nil Customer.find_by_address(missing_address)
597 end
598
599 def test_find_by_two_attributes_that_are_both_aggregates
600 balance = customers(:david).balance
601 address = customers(:david).address
602 assert_kind_of Money, balance
603 assert_kind_of Address, address
604 found_customer = Customer.find_by_balance_and_address(balance, address)
605 assert_equal customers(:david), found_customer
606 end
607
608 def test_find_by_two_attributes_with_one_being_an_aggregate
609 balance = customers(:david).balance
610 assert_kind_of Money, balance
611 found_customer = Customer.find_by_balance_and_name(balance, customers(:david).name)
612 assert_equal customers(:david), found_customer
613 end
614
615 def test_dynamic_finder_on_one_attribute_with_conditions_caches_method
616 # ensure this test can run independently of order
617 class << Account; self; end.send(:remove_method, :find_by_credit_limit) if Account.public_methods.any? { |m| m.to_s == 'find_by_credit_limit' }
618 assert !Account.public_methods.any? { |m| m.to_s == 'find_by_credit_limit' }
619 a = Account.find_by_credit_limit(50, :conditions => ['firm_id = ?', 6])
620 assert Account.public_methods.any? { |m| m.to_s == 'find_by_credit_limit' }
621 end
622
623 def test_dynamic_finder_on_one_attribute_with_conditions_returns_same_results_after_caching
624 # ensure this test can run independently of order
625 class << Account; self; end.send(:remove_method, :find_by_credit_limit) if Account.public_methods.any? { |m| m.to_s == 'find_by_credit_limit' }
626 a = Account.find_by_credit_limit(50, :conditions => ['firm_id = ?', 6])
627 assert_equal a, Account.find_by_credit_limit(50, :conditions => ['firm_id = ?', 6]) # find_by_credit_limit has been cached
628 end
629
630 def test_find_by_one_attribute_with_several_options
631 assert_equal accounts(:unknown), Account.find_by_credit_limit(50, :order => 'id DESC', :conditions => ['id != ?', 3])
632 end
633
634 def test_find_by_one_missing_attribute
635 assert_raise(NoMethodError) { Topic.find_by_undertitle("The First Topic!") }
636 end
637
638 def test_find_by_invalid_method_syntax
639 assert_raise(NoMethodError) { Topic.fail_to_find_by_title("The First Topic") }
640 assert_raise(NoMethodError) { Topic.find_by_title?("The First Topic") }
641 assert_raise(NoMethodError) { Topic.fail_to_find_or_create_by_title("Nonexistent Title") }
642 assert_raise(NoMethodError) { Topic.find_or_create_by_title?("Nonexistent Title") }
643 end
644
645 def test_find_by_two_attributes
646 assert_equal topics(:first), Topic.find_by_title_and_author_name("The First Topic", "David")
647 assert_nil Topic.find_by_title_and_author_name("The First Topic", "Mary")
648 end
649
650 def test_find_last_by_one_attribute
651 assert_equal Topic.last, Topic.find_last_by_title(Topic.last.title)
652 assert_nil Topic.find_last_by_title("A title with no matches")
653 end
654
655 def test_find_last_by_one_attribute_caches_dynamic_finder
656 # ensure this test can run independently of order
657 class << Topic; self; end.send(:remove_method, :find_last_by_title) if Topic.public_methods.any? { |m| m.to_s == 'find_last_by_title' }
658 assert !Topic.public_methods.any? { |m| m.to_s == 'find_last_by_title' }
659 t = Topic.find_last_by_title(Topic.last.title)
660 assert Topic.public_methods.any? { |m| m.to_s == 'find_last_by_title' }
661 end
662
663 def test_find_last_by_invalid_method_syntax
664 assert_raise(NoMethodError) { Topic.fail_to_find_last_by_title("The First Topic") }
665 assert_raise(NoMethodError) { Topic.find_last_by_title?("The First Topic") }
666 end
667
668 def test_find_last_by_one_attribute_with_several_options
669 assert_equal accounts(:signals37), Account.find_last_by_credit_limit(50, :order => 'id DESC', :conditions => ['id != ?', 3])
670 end
671
672 def test_find_last_by_one_missing_attribute
673 assert_raise(NoMethodError) { Topic.find_last_by_undertitle("The Last Topic!") }
674 end
675
676 def test_find_last_by_two_attributes
677 topic = Topic.last
678 assert_equal topic, Topic.find_last_by_title_and_author_name(topic.title, topic.author_name)
679 assert_nil Topic.find_last_by_title_and_author_name(topic.title, "Anonymous")
680 end
681
682 def test_find_all_by_one_attribute
683 topics = Topic.find_all_by_content("Have a nice day")
684 assert_equal 2, topics.size
685 assert topics.include?(topics(:first))
686
687 assert_equal [], Topic.find_all_by_title("The First Topic!!")
688 end
689
690 def test_find_all_by_one_attribute_that_is_an_aggregate
691 balance = customers(:david).balance
692 assert_kind_of Money, balance
693 found_customers = Customer.find_all_by_balance(balance)
694 assert_equal 1, found_customers.size
695 assert_equal customers(:david), found_customers.first
696 end
697
698 def test_find_all_by_two_attributes_that_are_both_aggregates
699 balance = customers(:david).balance
700 address = customers(:david).address
701 assert_kind_of Money, balance
702 assert_kind_of Address, address
703 found_customers = Customer.find_all_by_balance_and_address(balance, address)
704 assert_equal 1, found_customers.size
705 assert_equal customers(:david), found_customers.first
706 end
707
708 def test_find_all_by_two_attributes_with_one_being_an_aggregate
709 balance = customers(:david).balance
710 assert_kind_of Money, balance
711 found_customers = Customer.find_all_by_balance_and_name(balance, customers(:david).name)
712 assert_equal 1, found_customers.size
713 assert_equal customers(:david), found_customers.first
714 end
715
716 def test_find_all_by_one_attribute_with_options
717 topics = Topic.find_all_by_content("Have a nice day", :order => "id DESC")
718 assert topics(:first), topics.last
719
720 topics = Topic.find_all_by_content("Have a nice day", :order => "id")
721 assert topics(:first), topics.first
722 end
723
724 def test_find_all_by_array_attribute
725 assert_equal 2, Topic.find_all_by_title(["The First Topic", "The Second Topic of the day"]).size
726 end
727
728 def test_find_all_by_boolean_attribute
729 topics = Topic.find_all_by_approved(false)
730 assert_equal 1, topics.size
731 assert topics.include?(topics(:first))
732
733 topics = Topic.find_all_by_approved(true)
734 assert_equal 3, topics.size
735 assert topics.include?(topics(:second))
736 end
737
738 def test_find_by_nil_attribute
739 topic = Topic.find_by_last_read nil
740 assert_not_nil topic
741 assert_nil topic.last_read
742 end
743
744 def test_find_all_by_nil_attribute
745 topics = Topic.find_all_by_last_read nil
746 assert_equal 3, topics.size
747 assert topics.collect(&:last_read).all?(&:nil?)
748 end
749
750 def test_find_by_nil_and_not_nil_attributes
751 topic = Topic.find_by_last_read_and_author_name nil, "Mary"
752 assert_equal "Mary", topic.author_name
753 end
754
755 def test_find_all_by_nil_and_not_nil_attributes
756 topics = Topic.find_all_by_last_read_and_author_name nil, "Mary"
757 assert_equal 1, topics.size
758 assert_equal "Mary", topics[0].author_name
759 end
760
761 def test_find_or_create_from_one_attribute
762 number_of_companies = Company.count
763 sig38 = Company.find_or_create_by_name("38signals")
764 assert_equal number_of_companies + 1, Company.count
765 assert_equal sig38, Company.find_or_create_by_name("38signals")
766 assert !sig38.new_record?
767 end
768
769 def test_find_or_create_from_two_attributes
770 number_of_topics = Topic.count
771 another = Topic.find_or_create_by_title_and_author_name("Another topic","John")
772 assert_equal number_of_topics + 1, Topic.count
773 assert_equal another, Topic.find_or_create_by_title_and_author_name("Another topic", "John")
774 assert !another.new_record?
775 end
776
777 def test_find_or_create_from_two_attributes_with_one_being_an_aggregate
778 number_of_customers = Customer.count
779 created_customer = Customer.find_or_create_by_balance_and_name(Money.new(123), "Elizabeth")
780 assert_equal number_of_customers + 1, Customer.count
781 assert_equal created_customer, Customer.find_or_create_by_balance(Money.new(123), "Elizabeth")
782 assert !created_customer.new_record?
783 end
784
785 def test_find_or_create_from_one_attribute_and_hash
786 number_of_companies = Company.count
787 sig38 = Company.find_or_create_by_name({:name => "38signals", :firm_id => 17, :client_of => 23})
788 assert_equal number_of_companies + 1, Company.count
789 assert_equal sig38, Company.find_or_create_by_name({:name => "38signals", :firm_id => 17, :client_of => 23})
790 assert !sig38.new_record?
791 assert_equal "38signals", sig38.name
792 assert_equal 17, sig38.firm_id
793 assert_equal 23, sig38.client_of
794 end
795
796 def test_find_or_create_from_one_aggregate_attribute
797 number_of_customers = Customer.count
798 created_customer = Customer.find_or_create_by_balance(Money.new(123))
799 assert_equal number_of_customers + 1, Customer.count
800 assert_equal created_customer, Customer.find_or_create_by_balance(Money.new(123))
801 assert !created_customer.new_record?
802 end
803
804 def test_find_or_create_from_one_aggregate_attribute_and_hash
805 number_of_customers = Customer.count
806 balance = Money.new(123)
807 name = "Elizabeth"
808 created_customer = Customer.find_or_create_by_balance({:balance => balance, :name => name})
809 assert_equal number_of_customers + 1, Customer.count
810 assert_equal created_customer, Customer.find_or_create_by_balance({:balance => balance, :name => name})
811 assert !created_customer.new_record?
812 assert_equal balance, created_customer.balance
813 assert_equal name, created_customer.name
814 end
815
816 def test_find_or_initialize_from_one_attribute
817 sig38 = Company.find_or_initialize_by_name("38signals")
818 assert_equal "38signals", sig38.name
819 assert sig38.new_record?
820 end
821
822 def test_find_or_initialize_from_one_aggregate_attribute
823 new_customer = Customer.find_or_initialize_by_balance(Money.new(123))
824 assert_equal 123, new_customer.balance.amount
825 assert new_customer.new_record?
826 end
827
828 def test_find_or_initialize_from_one_attribute_should_not_set_attribute_even_when_protected
829 c = Company.find_or_initialize_by_name({:name => "Fortune 1000", :rating => 1000})
830 assert_equal "Fortune 1000", c.name
831 assert_not_equal 1000, c.rating
832 assert c.valid?
833 assert c.new_record?
834 end
835
836 def test_find_or_create_from_one_attribute_should_set_not_attribute_even_when_protected
837 c = Company.find_or_create_by_name({:name => "Fortune 1000", :rating => 1000})
838 assert_equal "Fortune 1000", c.name
839 assert_not_equal 1000, c.rating
840 assert c.valid?
841 assert !c.new_record?
842 end
843
844 def test_find_or_initialize_from_one_attribute_should_set_attribute_even_when_protected
845 c = Company.find_or_initialize_by_name_and_rating("Fortune 1000", 1000)
846 assert_equal "Fortune 1000", c.name
847 assert_equal 1000, c.rating
848 assert c.valid?
849 assert c.new_record?
850 end
851
852 def test_find_or_create_from_one_attribute_should_set_attribute_even_when_protected
853 c = Company.find_or_create_by_name_and_rating("Fortune 1000", 1000)
854 assert_equal "Fortune 1000", c.name
855 assert_equal 1000, c.rating
856 assert c.valid?
857 assert !c.new_record?
858 end
859
860 def test_find_or_initialize_should_set_protected_attributes_if_given_as_block
861 c = Company.find_or_initialize_by_name(:name => "Fortune 1000") { |f| f.rating = 1000 }
862 assert_equal "Fortune 1000", c.name
863 assert_equal 1000.to_f, c.rating.to_f
864 assert c.valid?
865 assert c.new_record?
866 end
867
868 def test_find_or_create_should_set_protected_attributes_if_given_as_block
869 c = Company.find_or_create_by_name(:name => "Fortune 1000") { |f| f.rating = 1000 }
870 assert_equal "Fortune 1000", c.name
871 assert_equal 1000.to_f, c.rating.to_f
872 assert c.valid?
873 assert !c.new_record?
874 end
875
876 def test_find_or_create_should_work_with_block_on_first_call
877 class << Company
878 undef_method(:find_or_create_by_name) if method_defined?(:find_or_create_by_name)
879 end
880 c = Company.find_or_create_by_name(:name => "Fortune 1000") { |f| f.rating = 1000 }
881 assert_equal "Fortune 1000", c.name
882 assert_equal 1000.to_f, c.rating.to_f
883 assert c.valid?
884 assert !c.new_record?
885 end
886
887 def test_dynamic_find_or_initialize_from_one_attribute_caches_method
888 class << Company; self; end.send(:remove_method, :find_or_initialize_by_name) if Company.public_methods.any? { |m| m.to_s == 'find_or_initialize_by_name' }
889 assert !Company.public_methods.any? { |m| m.to_s == 'find_or_initialize_by_name' }
890 sig38 = Company.find_or_initialize_by_name("38signals")
891 assert Company.public_methods.any? { |m| m.to_s == 'find_or_initialize_by_name' }
892 end
893
894 def test_find_or_initialize_from_two_attributes
895 another = Topic.find_or_initialize_by_title_and_author_name("Another topic","John")
896 assert_equal "Another topic", another.title
897 assert_equal "John", another.author_name
898 assert another.new_record?
899 end
900
901 def test_find_or_initialize_from_one_aggregate_attribute_and_one_not
902 new_customer = Customer.find_or_initialize_by_balance_and_name(Money.new(123), "Elizabeth")
903 assert_equal 123, new_customer.balance.amount
904 assert_equal "Elizabeth", new_customer.name
905 assert new_customer.new_record?
906 end
907
908 def test_find_or_initialize_from_one_attribute_and_hash
909 sig38 = Company.find_or_initialize_by_name({:name => "38signals", :firm_id => 17, :client_of => 23})
910 assert_equal "38signals", sig38.name
911 assert_equal 17, sig38.firm_id
912 assert_equal 23, sig38.client_of
913 assert sig38.new_record?
914 end
915
916 def test_find_or_initialize_from_one_aggregate_attribute_and_hash
917 balance = Money.new(123)
918 name = "Elizabeth"
919 new_customer = Customer.find_or_initialize_by_balance({:balance => balance, :name => name})
920 assert_equal balance, new_customer.balance
921 assert_equal name, new_customer.name
922 assert new_customer.new_record?
923 end
924
925 def test_find_with_bad_sql
926 assert_raise(ActiveRecord::StatementInvalid) { Topic.find_by_sql "select 1 from badtable" }
927 end
928
929 def test_find_with_invalid_params
930 assert_raise(ArgumentError) { Topic.find :first, :join => "It should be `joins'" }
931 assert_raise(ArgumentError) { Topic.find :first, :conditions => '1 = 1', :join => "It should be `joins'" }
932 end
933
934 def test_dynamic_finder_with_invalid_params
935 assert_raise(ArgumentError) { Topic.find_by_title 'No Title', :join => "It should be `joins'" }
936 end
937
938 def test_find_all_with_limit
939 first_five_developers = Developer.find :all, :order => 'id ASC', :limit => 5
940 assert_equal 5, first_five_developers.length
941 assert_equal 'David', first_five_developers.first.name
942 assert_equal 'fixture_5', first_five_developers.last.name
943
944 no_developers = Developer.find :all, :order => 'id ASC', :limit => 0
945 assert_equal 0, no_developers.length
946 end
947
948 def test_find_all_with_limit_and_offset
949 first_three_developers = Developer.find :all, :order => 'id ASC', :limit => 3, :offset => 0
950 second_three_developers = Developer.find :all, :order => 'id ASC', :limit => 3, :offset => 3
951 last_two_developers = Developer.find :all, :order => 'id ASC', :limit => 2, :offset => 8
952
953 assert_equal 3, first_three_developers.length
954 assert_equal 3, second_three_developers.length
955 assert_equal 2, last_two_developers.length
956
957 assert_equal 'David', first_three_developers.first.name
958 assert_equal 'fixture_4', second_three_developers.first.name
959 assert_equal 'fixture_9', last_two_developers.first.name
960 end
961
962 def test_find_all_with_limit_and_offset_and_multiple_order_clauses
963 first_three_posts = Post.find :all, :order => 'author_id, id', :limit => 3, :offset => 0
964 second_three_posts = Post.find :all, :order => ' author_id,id ', :limit => 3, :offset => 3
965 last_posts = Post.find :all, :order => ' author_id, id ', :limit => 3, :offset => 6
966
967 assert_equal [[0,3],[1,1],[1,2]], first_three_posts.map { |p| [p.author_id, p.id] }
968 assert_equal [[1,4],[1,5],[1,6]], second_three_posts.map { |p| [p.author_id, p.id] }
969 assert_equal [[2,7]], last_posts.map { |p| [p.author_id, p.id] }
970 end
971
972 def test_find_all_with_join
973 developers_on_project_one = Developer.find(
974 :all,
975 :joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id',
976 :conditions => 'project_id=1'
977 )
978 assert_equal 3, developers_on_project_one.length
979 developer_names = developers_on_project_one.map { |d| d.name }
980 assert developer_names.include?('David')
981 assert developer_names.include?('Jamis')
982 end
983
984 def test_joins_dont_clobber_id
985 first = Firm.find(
986 :first,
987 :joins => 'INNER JOIN companies AS clients ON clients.firm_id = companies.id',
988 :conditions => 'companies.id = 1'
989 )
990 assert_equal 1, first.id
991 end
992
993 def test_joins_with_string_array
994 person_with_reader_and_post = Post.find(
995 :all,
996 :joins => [
997 "INNER JOIN categorizations ON categorizations.post_id = posts.id",
998 "INNER JOIN categories ON categories.id = categorizations.category_id AND categories.type = 'SpecialCategory'"
999 ]
1000 )
1001 assert_equal 1, person_with_reader_and_post.size
1002 end
1003
1004 def test_find_by_id_with_conditions_with_or
1005 assert_nothing_raised do
1006 Post.find([1,2,3],
1007 :conditions => "posts.id <= 3 OR posts.#{QUOTED_TYPE} = 'Post'")
1008 end
1009 end
1010
1011 # http://dev.rubyonrails.org/ticket/6778
1012 def test_find_ignores_previously_inserted_record
1013 post = Post.create!(:title => 'test', :body => 'it out')
1014 assert_equal [], Post.find_all_by_id(nil)
1015 end
1016
1017 def test_find_by_empty_ids
1018 assert_equal [], Post.find([])
1019 end
1020
1021 def test_find_by_empty_in_condition
1022 assert_equal [], Post.find(:all, :conditions => ['id in (?)', []])
1023 end
1024
1025 def test_find_by_records
1026 p1, p2 = Post.find(:all, :limit => 2, :order => 'id asc')
1027 assert_equal [p1, p2], Post.find(:all, :conditions => ['id in (?)', [p1, p2]], :order => 'id asc')
1028 assert_equal [p1, p2], Post.find(:all, :conditions => ['id in (?)', [p1, p2.id]], :order => 'id asc')
1029 end
1030
1031 def test_select_value
1032 assert_equal "37signals", Company.connection.select_value("SELECT name FROM companies WHERE id = 1")
1033 assert_nil Company.connection.select_value("SELECT name FROM companies WHERE id = -1")
1034 # make sure we didn't break count...
1035 assert_equal 0, Company.count_by_sql("SELECT COUNT(*) FROM companies WHERE name = 'Halliburton'")
1036 assert_equal 1, Company.count_by_sql("SELECT COUNT(*) FROM companies WHERE name = '37signals'")
1037 end
1038
1039 def test_select_values
1040 assert_equal ["1","2","3","4","5","6","7","8","9"], Company.connection.select_values("SELECT id FROM companies ORDER BY id").map! { |i| i.to_s }
1041 assert_equal ["37signals","Summit","Microsoft", "Flamboyant Software", "Ex Nihilo", "RailsCore", "Leetsoft", "Jadedpixel", "Odegy"], Company.connection.select_values("SELECT name FROM companies ORDER BY id")
1042 end
1043
1044 def test_select_rows
1045 assert_equal(
1046 [["1", nil, nil, "37signals"],
1047 ["2", "1", "2", "Summit"],
1048 ["3", "1", "1", "Microsoft"]],
1049 Company.connection.select_rows("SELECT id, firm_id, client_of, name FROM companies WHERE id IN (1,2,3) ORDER BY id").map! {|i| i.map! {|j| j.to_s unless j.nil?}})
1050 assert_equal [["1", "37signals"], ["2", "Summit"], ["3", "Microsoft"]],
1051 Company.connection.select_rows("SELECT id, name FROM companies WHERE id IN (1,2,3) ORDER BY id").map! {|i| i.map! {|j| j.to_s unless j.nil?}}
1052 end
1053
1054 def test_find_with_order_on_included_associations_with_construct_finder_sql_for_association_limiting_and_is_distinct
1055 assert_equal 2, Post.find(:all, :include => { :authors => :author_address }, :order => ' author_addresses.id DESC ', :limit => 2).size
1056
1057 assert_equal 3, Post.find(:all, :include => { :author => :author_address, :authors => :author_address},
1058 :order => ' author_addresses_authors.id DESC ', :limit => 3).size
1059 end
1060
1061 def test_with_limiting_with_custom_select
1062 posts = Post.find(:all, :include => :author, :select => ' posts.*, authors.id as "author_id"', :limit => 3, :order => 'posts.id')
1063 assert_equal 3, posts.size
1064 assert_equal [0, 1, 1], posts.map(&:author_id).sort
1065 end
1066
1067 def test_finder_with_scoped_from
1068 all_topics = Topic.all
1069
1070 Topic.with_scope(:find => { :from => 'fake_topics' }) do
1071 assert_equal all_topics, Topic.all(:from => 'topics')
1072 end
1073 end
1074
1075 protected
1076 def bind(statement, *vars)
1077 if vars.first.is_a?(Hash)
1078 ActiveRecord::Base.send(:replace_named_bind_variables, statement, vars.first)
1079 else
1080 ActiveRecord::Base.send(:replace_bind_variables, statement, vars)
1081 end
1082 end
1083 end