From eb72e62c3042c0df989d951b1d12291395ebdb8e Mon Sep 17 00:00:00 2001 From: Jon Leighton Date: Fri, 19 Oct 2012 13:18:47 +0100 Subject: 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 --- activerecord/test/cases/relations_test.rb | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'activerecord/test/cases/relations_test.rb') 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 -- cgit v1.2.3