From 84dad446c6a23a15f67b9d558e8039891a008bff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Mej=C3=ADa?= Date: Sat, 27 Aug 2011 23:10:25 -0500 Subject: Adding first_or_create, first_or_create!, first_or_new and first_or_build to Active Record. This let's you write things like: User.where(:first_name => "Scarlett").first_or_create!(:last_name => "Johansson", :hot => true) Related to #2420. --- activerecord/test/cases/base_test.rb | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) (limited to 'activerecord/test/cases/base_test.rb') diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 1e647b5970..02a4644cd2 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -277,6 +277,37 @@ class BasicsTest < ActiveRecord::TestCase assert_equal(true, cb.frickinawesome) end + def test_first_or_create + parrot = Bird.first_or_create(:color => 'green', :name => 'parrot') + assert parrot.persisted? + the_same_parrot = Bird.first_or_create(:color => 'yellow', :name => 'macaw') + assert_equal parrot, the_same_parrot + end + + def test_first_or_create_bang + assert_raises(ActiveRecord::RecordInvalid) { Bird.first_or_create! } + parrot = Bird.first_or_create!(:color => 'green', :name => 'parrot') + assert parrot.persisted? + the_same_parrot = Bird.first_or_create!(:color => 'yellow', :name => 'macaw') + assert_equal parrot, the_same_parrot + end + + def test_first_or_new + parrot = Bird.first_or_new(:color => 'green', :name => 'parrot') + assert_kind_of Bird, parrot + assert !parrot.persisted? + assert parrot.new_record? + assert parrot.valid? + end + + def test_first_or_build + parrot = Bird.first_or_build(:color => 'green', :name => 'parrot') + assert_kind_of Bird, parrot + assert !parrot.persisted? + assert parrot.new_record? + assert parrot.valid? + end + def test_load topics = Topic.find(:all, :order => 'id') assert_equal(4, topics.size) -- cgit v1.2.3