aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/test/cases/relations_test.rb
diff options
context:
space:
mode:
authorJon Leighton <j@jonathanleighton.com>2012-10-19 13:18:47 +0100
committerJon Leighton <j@jonathanleighton.com>2012-10-19 13:18:47 +0100
commiteb72e62c3042c0df989d951b1d12291395ebdb8e (patch)
tree258c2dc61b2e146fb2cdef47d2799ea9dbdaa004 /activerecord/test/cases/relations_test.rb
parent0d7b0f0183ce9f1bfc524cf6afd5d7de852ebc76 (diff)
downloadrails-eb72e62c3042c0df989d951b1d12291395ebdb8e.tar.gz
rails-eb72e62c3042c0df989d951b1d12291395ebdb8e.tar.bz2
rails-eb72e62c3042c0df989d951b1d12291395ebdb8e.zip
Add Relation#find_or_create_by and friends
This is similar to #first_or_create, but slightly different and a nicer API. See the CHANGELOG/docs in the commit. Fixes #7853
Diffstat (limited to 'activerecord/test/cases/relations_test.rb')
-rw-r--r--activerecord/test/cases/relations_test.rb23
1 files changed, 23 insertions, 0 deletions
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index fdbc0a3fdb..7504da01d5 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -1058,6 +1058,29 @@ class RelationTest < ActiveRecord::TestCase
assert_equal 'parrot', parrot.name
end
+ def test_find_or_create_by
+ assert_nil Bird.find_by(name: 'bob')
+
+ bird = Bird.find_or_create_by(name: 'bob')
+ assert bird.persisted?
+
+ assert_equal bird, Bird.find_or_create_by(name: 'bob')
+ end
+
+ def test_find_or_create_by!
+ assert_raises(ActiveRecord::RecordInvalid) { Bird.find_or_create_by!(color: 'green') }
+ end
+
+ def test_find_or_initialize_by
+ assert_nil Bird.find_by(name: 'bob')
+
+ bird = Bird.find_or_initialize_by(name: 'bob')
+ assert bird.new_record?
+ bird.save!
+
+ assert_equal bird, Bird.find_or_initialize_by(name: 'bob')
+ end
+
def test_explicit_create_scope
hens = Bird.where(:name => 'hen')
assert_equal 'hen', hens.new.name