aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/test/cases/relations_test.rb
diff options
context:
space:
mode:
authorDavid Heinemeier Hansson <david@loudthinking.com>2018-02-14 16:51:15 -0800
committerGitHub <noreply@github.com>2018-02-14 16:51:15 -0800
commitfe6adf43e124f4c9132e5a88a80ebba3f10fd2cb (patch)
tree9b038131edd2aa8735e7996a9646f927a354f0c2 /activerecord/test/cases/relations_test.rb
parentfbc7d63ab46a50bb716dd96059fc4e898b0b865f (diff)
downloadrails-fe6adf43e124f4c9132e5a88a80ebba3f10fd2cb.tar.gz
rails-fe6adf43e124f4c9132e5a88a80ebba3f10fd2cb.tar.bz2
rails-fe6adf43e124f4c9132e5a88a80ebba3f10fd2cb.zip
Add #create_or_find_by to lean on unique constraints (#31989)
Add #create_or_find_by to lean on unique constraints
Diffstat (limited to 'activerecord/test/cases/relations_test.rb')
-rw-r--r--activerecord/test/cases/relations_test.rb29
1 files changed, 29 insertions, 0 deletions
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index bc7c54dbe0..18e0bed5b6 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -22,6 +22,7 @@ require "models/reader"
require "models/category"
require "models/categorization"
require "models/edge"
+require "models/subscriber"
class RelationTest < ActiveRecord::TestCase
fixtures :authors, :author_addresses, :topics, :entrants, :developers, :companies, :developers_projects, :accounts, :categories, :categorizations, :categories_posts, :posts, :comments, :tags, :taggings, :cars, :minivans
@@ -1349,6 +1350,34 @@ class RelationTest < ActiveRecord::TestCase
assert_raises(ActiveRecord::RecordInvalid) { Bird.find_or_create_by!(color: "green") }
end
+ def test_create_or_find_by
+ assert_nil Subscriber.find_by(nick: "bob")
+
+ subscriber = Subscriber.create!(nick: "bob")
+
+ assert_equal subscriber, Subscriber.create_or_find_by(nick: "bob")
+ assert_not_equal subscriber, Subscriber.create_or_find_by(nick: "cat")
+ end
+
+ def test_create_or_find_by_with_non_unique_attributes
+ Subscriber.create!(nick: "bob", name: "the builder")
+
+ assert_raises(ActiveRecord::RecordNotFound) do
+ Subscriber.create_or_find_by(nick: "bob", name: "the cat")
+ end
+ end
+
+ def test_create_or_find_by_within_transaction
+ assert_nil Subscriber.find_by(nick: "bob")
+
+ subscriber = Subscriber.create!(nick: "bob")
+
+ Subscriber.transaction do
+ assert_equal subscriber, Subscriber.create_or_find_by(nick: "bob")
+ assert_not_equal subscriber, Subscriber.create_or_find_by(nick: "cat")
+ end
+ end
+
def test_find_or_initialize_by
assert_nil Bird.find_by(name: "bob")