2 require 'models/author'
3 require 'models/categorization'
4 require 'models/comment'
5 require 'models/company'
8 require 'models/entrant'
9 require 'models/developer'
11 require 'models/customer'
13 require 'models/categorization'
15 class DynamicFinderMatchTest
< ActiveRecord
::TestCase
16 def test_find_no_match
17 assert_nil ActiveRecord
::DynamicFinderMatch.match("not_a_finder")
21 match
= ActiveRecord
::DynamicFinderMatch.match("find_by_age_and_sex_and_location")
24 assert_equal
:first, match
.finder
25 assert_equal
%w(age sex location
), match
.attribute_names
29 match
= ActiveRecord
::DynamicFinderMatch.match("find_by_age_and_sex_and_location!")
33 assert_equal
:first, match
.finder
34 assert_equal
%w(age sex location
), match
.attribute_names
38 match
= ActiveRecord
::DynamicFinderMatch.match("find_all_by_age_and_sex_and_location")
41 assert_equal
:all, match
.finder
42 assert_equal
%w(age sex location
), match
.attribute_names
45 def test_find_or_initialize_by
46 match
= ActiveRecord
::DynamicFinderMatch.match("find_or_initialize_by_age_and_sex_and_location")
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
55 def test_find_or_create_by
56 match
= ActiveRecord
::DynamicFinderMatch.match("find_or_create_by_age_and_sex_and_location")
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
66 class FinderTest
< ActiveRecord
::TestCase
67 fixtures
:companies, :topics, :entrants, :developers, :developers_projects, :posts, :comments, :accounts, :authors, :customers
70 assert_equal(topics(:first).title
, Topic
.find(1).title
)
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
)
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)
88 assert
!Topic
.exists
?("foo")
89 rescue ActiveRecord
::StatementInvalid
90 # PostgreSQL complains about string comparison with integer field
95 assert_raise(NoMethodError
) { Topic
.exists
?([1,2]) }
98 def test_exists_returns_true_with_one_record_and_no_args
102 def test_does_not_exist_with_empty_table_and_no_args_given
104 assert
!Topic
.exists
?
107 def test_exists_with_aggregate_having_three_mappings
108 existing_address
= customers(:david).address
109 assert Customer
.exists
?(:address => existing_address
)
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
))
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
)
128 assert_equal
2, Topic
.find(1, 2).size
129 assert_equal
topics(:second).title
, Topic
.find([2]).first
.title
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
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
144 def test_find_an_empty_array
145 assert_equal
[], Topic
.find([])
148 def test_find_by_ids_missing_one
149 assert_raise(ActiveRecord
::RecordNotFound) { Topic
.find(1, 2, 45) }
152 def test_find_all_with_limit
153 entrants
= Entrant
.find(:all, :order => "id ASC", :limit => 2)
155 assert_equal(2, entrants
.size
)
156 assert_equal(entrants(:first).name
, entrants
.first
.name
)
159 def test_find_all_with_prepared_limit_and_offset
160 entrants
= Entrant
.find(:all, :order => "id ASC", :limit => 2, :offset => 1)
162 assert_equal(2, entrants
.size
)
163 assert_equal(entrants(:second).name
, entrants
.first
.name
)
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
)
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
}
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
)
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
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 }
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 }
201 def test_find_with_entire_select_statement
202 topics
= Topic
.find_by_sql
"SELECT * FROM topics WHERE author_name = 'Mary'"
204 assert_equal(1, topics
.size
)
205 assert_equal(topics(:second).title
, topics
.first
.title
)
208 def test_find_with_prepared_select_statement
209 topics
= Topic
.find_by_sql
["SELECT * FROM topics WHERE author_name = ?", "Mary"]
211 assert_equal(1, topics
.size
)
212 assert_equal(topics(:second).title
, topics
.first
.title
)
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
221 first
= Topic
.find(:first, :conditions => "title = 'The First Topic'")
222 assert_equal(topics(:first).title
, first
.title
)
225 def test_find_first_failing
226 first
= Topic
.find(:first, :conditions => "title = 'The First Topic!'")
231 assert_equal
topics(:second).title
, Topic
.first(:conditions => "title = 'The Second Topic of the day'").title
234 def test_first_failing
235 assert_nil Topic
.first(:conditions => "title = 'The Second Topic of the day!'")
238 def test_unexisting_record_exception_handling
239 assert_raise(ActiveRecord
::RecordNotFound) {
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")
256 def test_find_on_blank_conditions
257 [nil, " ", [], {}].each
do |blank
|
258 assert_nothing_raised
{ Topic
.find(:first, :conditions => blank
) }
262 def test_find_on_blank_bind_conditions
263 [ [""], ["",{}] ].each
do |blank
|
264 assert_nothing_raised
{ Topic
.find(:first, :conditions => blank
) }
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]) }
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 }) }
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 }) }
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 }}) }
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
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
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
})
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
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 }) }
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 }) }
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
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 }) }
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
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
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
355 def test_hash_condition_find_malformed
356 assert_raise(ActiveRecord
::StatementInvalid) {
357 Company
.find(:first, :conditions => { :id => 2, :dhh => true })
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" })
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')
372 def test_hash_condition_find_with_nil
373 topic
= Topic
.find(:first, :conditions => { :last_read => nil } )
375 assert_nil topic
.last_read
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
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
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
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
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
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
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])
428 assert_raise(ActiveRecord
::PreparedStatementInvalid) {
429 Company
.find(:first, :conditions => ["id=?", 2, 3, 4])
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"])
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"}])
444 assert_nothing_raised
{ bind
'' }
445 assert_raise(ActiveRecord
::PreparedStatementInvalid) { bind
'', 1 }
447 assert_raise(ActiveRecord
::PreparedStatementInvalid) { bind
'?' }
448 assert_nothing_raised
{ bind
'?', 1 }
449 assert_raise(ActiveRecord
::PreparedStatementInvalid) { bind
'?', 1, 1 }
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
456 assert_nothing_raised
{ bind("'+00:00'", :foo => "bar") }
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
464 def test_bind_enumerable
465 quoted_abc
= %(#{ActiveRecord::Base.connection.quote('a')},#{ActiveRecord::Base.connection.quote('b')},#{ActiveRecord::Base.connection.quote('c')})
467 assert_equal '1,2,3', bind('?', [1, 2, 3])
468 assert_equal quoted_abc, bind('?', %w(a b c))
470 assert_equal '1,2,3', bind(':a', :a => [1, 2, 3])
471 assert_equal quoted_abc, bind(':a', :a => %w(a b c)) # '
474 assert_equal '1,2,3', bind('?', Set.new([1, 2, 3]))
475 assert_equal quoted_abc, bind('?', Set.new(%w(a b c)))
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))) # '
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 (?)', [])
489 assert_equal ActiveRecord::Base.connection.quote(''), bind('?', '')
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)
502 o = Struct.new(:quoted_id).new(1)
503 assert_equal '1', bind('?', o)
506 assert_equal '1,1,1', bind('?', os)
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
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")
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]))
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]))
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!")
536 Topic.expects(:find).with(:last, :conditions => { :title => 'The Last Topic!' })
537 Topic.find_last_by_title("The Last Topic!")
539 Topic.expects(:find).with(:all, :conditions => { :title => 'A Topic.' })
540 Topic.find_all_by_title("A Topic.")
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!')
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!")
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!") }
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' }
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
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')
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])
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
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)
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
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
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' }
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
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])
634 def test_find_by_one_missing_attribute
635 assert_raise(NoMethodError) { Topic.find_by_undertitle("The First Topic!") }
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") }
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")
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")
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' }
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") }
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])
672 def test_find_last_by_one_missing_attribute
673 assert_raise(NoMethodError) { Topic.find_last_by_undertitle("The Last Topic!") }
676 def test_find_last_by_two_attributes
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")
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))
687 assert_equal [], Topic.find_all_by_title("The First Topic!!")
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
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
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
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
720 topics = Topic.find_all_by_content("Have a nice day", :order => "id")
721 assert topics(:first), topics.first
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
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))
733 topics = Topic.find_all_by_approved(true)
734 assert_equal 3, topics.size
735 assert topics.include?(topics(:second))
738 def test_find_by_nil_attribute
739 topic = Topic.find_by_last_read nil
741 assert_nil topic.last_read
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?)
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
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
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?
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?
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?
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
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?
804 def test_find_or_create_from_one_aggregate_attribute_and_hash
805 number_of_customers = Customer.count
806 balance = Money.new(123)
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
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?
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?
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
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
841 assert !c.new_record?
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
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
857 assert !c.new_record?
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
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
873 assert !c.new_record?
876 def test_find_or_create_should_work_with_block_on_first_call
878 undef_method(:find_or_create_by_name) if method_defined?(:find_or_create_by_name)
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
884 assert !c.new_record?
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' }
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?
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?
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?
916 def test_find_or_initialize_from_one_aggregate_attribute_and_hash
917 balance = Money.new(123)
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?
925 def test_find_with_bad_sql
926 assert_raise(ActiveRecord::StatementInvalid) { Topic.find_by_sql "select 1 from badtable" }
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'" }
934 def test_dynamic_finder_with_invalid_params
935 assert_raise(ArgumentError) { Topic.find_by_title 'No Title', :join => "It should be `joins'" }
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
944 no_developers = Developer.find :all, :order => 'id ASC', :limit => 0
945 assert_equal 0, no_developers.length
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
953 assert_equal 3, first_three_developers.length
954 assert_equal 3, second_three_developers.length
955 assert_equal 2, last_two_developers.length
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
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
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] }
972 def test_find_all_with_join
973 developers_on_project_one = Developer.find(
975 :joins => 'LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id',
976 :conditions => 'project_id=1'
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')
984 def test_joins_dont_clobber_id
987 :joins => 'INNER JOIN companies AS clients ON clients.firm_id = companies.id',
988 :conditions => 'companies.id = 1'
990 assert_equal 1, first.id
993 def test_joins_with_string_array
994 person_with_reader_and_post = Post.find(
997 "INNER JOIN categorizations ON categorizations.post_id = posts.id",
998 "INNER JOIN categories ON categories.id = categorizations.category_id AND categories.type = 'SpecialCategory'"
1001 assert_equal 1, person_with_reader_and_post.size
1004 def test_find_by_id_with_conditions_with_or
1005 assert_nothing_raised do
1007 :conditions => "posts.id <= 3 OR posts.#{QUOTED_TYPE} = 'Post'")
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)
1017 def test_find_by_empty_ids
1018 assert_equal [], Post.find([])
1021 def test_find_by_empty_in_condition
1022 assert_equal [], Post.find(:all, :conditions => ['id in (?)', []])
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')
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'")
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")
1044 def test_select_rows
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?}}
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
1057 assert_equal 3, Post.find(:all, :include => { :author => :author_address, :authors => :author_address},
1058 :order => ' author_addresses_authors.id DESC ', :limit => 3).size
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
1067 def test_finder_with_scoped_from
1068 all_topics = Topic.all
1070 Topic.with_scope(:find => { :from => 'fake_topics' }) do
1071 assert_equal all_topics, Topic.all(:from => 'topics')
1076 def bind(statement, *vars)
1077 if vars.first.is_a?(Hash)
1078 ActiveRecord::Base.send(:replace_named_bind_variables, statement, vars.first)
1080 ActiveRecord::Base.send(:replace_bind_variables, statement, vars)