Extended test cases in AR for methods accepting blocks

This commit is contained in:
Ghouse Mohamed 2022-04-03 22:52:53 +05:30
parent 926b803297
commit b3b781c50e
1 changed files with 53 additions and 0 deletions

View File

@ -1307,6 +1307,18 @@ class RelationTest < ActiveRecord::TestCase
green_birds.each { |bird| assert_predicate bird, :persisted? }
end
def test_create_with_block
sparrow = Bird.create do |bird|
bird.name = "sparrow"
bird.color = "grey"
end
assert_kind_of Bird, sparrow
assert_predicate sparrow, :persisted?
assert_equal "sparrow", sparrow.name
assert_equal "grey", sparrow.color
end
def test_create_bang_with_array
green_birds = Bird.where(color: "green").create!([{ name: "parrot" }, { name: "canary" }])
assert_equal ["parrot", "canary"], green_birds.map(&:name)
@ -1481,6 +1493,19 @@ class RelationTest < ActiveRecord::TestCase
assert_equal bird, Bird.create_with(color: "blue").find_or_create_by(name: "bob")
end
def test_find_or_create_by_with_block
assert_nil Bird.find_by(name: "bob")
bird = Bird.find_or_create_by(name: "bob") do |record|
record.color = "blue"
end
assert_predicate bird, :persisted?
assert_equal bird.name, "bob"
assert_equal bird.color, "blue"
assert_equal bird, Bird.find_or_create_by(name: "bob", color: "blue")
end
def test_find_or_create_by!
assert_raises(ActiveRecord::RecordInvalid) { Bird.find_or_create_by!(color: "green") }
end
@ -1494,6 +1519,20 @@ class RelationTest < ActiveRecord::TestCase
assert_not_equal subscriber, Subscriber.create_or_find_by(nick: "cat")
end
def test_create_or_find_by_with_block
assert_nil Subscriber.find_by(nick: "bob")
subscriber = Subscriber.create_or_find_by(nick: "bob") do |record|
record.name = "the builder"
end
assert_equal "bob", subscriber.nick
assert_equal "the builder", subscriber.name
assert_predicate subscriber, :persisted?
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_should_not_raise_due_to_validation_errors
assert_nothing_raised do
bird = Bird.create_or_find_by(color: "green")
@ -1562,6 +1601,20 @@ class RelationTest < ActiveRecord::TestCase
assert_equal bird, Bird.find_or_initialize_by(name: "bob")
end
def test_find_or_initialize_by_with_block
assert_nil Bird.find_by(name: "bob")
bird = Bird.find_or_initialize_by(name: "bob") do |record|
record.color = "blue"
end
assert_predicate bird, :new_record?
assert_equal bird.name, "bob"
assert_equal bird.color, "blue"
bird.save!
assert_equal bird, Bird.find_or_initialize_by(name: "bob", color: "blue")
end
def test_explicit_create_with
hens = Bird.where(name: "hen")
assert_equal "hen", hens.new.name