5
0
Fork 0
mirror of https://0xacab.org/sutty/sutty synced 2024-11-22 20:06:22 +00:00

testear la relación has_many

un artículo puede tener varios artículos, es la inversa de belongs_to

también eliminamos la memoización
This commit is contained in:
f 2021-05-13 19:48:41 -03:00
parent bda56e3c10
commit 817d5650f8
2 changed files with 50 additions and 11 deletions

View file

@ -6,14 +6,6 @@
# Localmente tenemos un Array de UUIDs. Remotamente tenemos una String
# apuntando a un Post, que se mantiene actualizado como el actual.
class MetadataHasMany < MetadataRelatedPosts
# Invalidar la relación anterior
def value_was=(new_value)
@had_many = nil
@has_many = nil
super(new_value)
end
def validate
super
@ -24,14 +16,16 @@ class MetadataHasMany < MetadataRelatedPosts
# Todos los Post relacionados
def has_many
@has_many ||= posts.where(uuid: value)
return default_value if value.blank?
posts.where(uuid: value)
end
# La relación anterior
def had_many
return [] if value_was.blank?
return default_value if value_was.blank?
@had_many ||= posts.where(uuid: value_was)
posts.where(uuid: value_was)
end
def inverse?

View file

@ -0,0 +1,45 @@
# frozen_string_literal: true
require 'test_helper'
require_relative 'metadata_test'
class MetadataHasManyTest < ActiveSupport::TestCase
include MetadataTest
test 'se pueden relacionar artículos' do
reply = @site.posts.create(layout: :post, title: SecureRandom.hex)
post = @site.posts.create(layout: :post, title: SecureRandom.hex, posts: [reply.uuid.value])
assert_equal post, reply.in_reply_to.belongs_to
assert_includes post.posts.has_many, reply
end
test 'se puede eliminar la relación' do
reply = @site.posts.create(layout: :post, title: SecureRandom.hex)
post = @site.posts.create(layout: :post, title: SecureRandom.hex, posts: [reply.uuid.value])
post.posts.value = []
post.save
assert_not_equal post, reply.in_reply_to.belongs_to
assert_equal post, reply.in_reply_to.belonged_to
assert_nil reply.in_reply_to.belongs_to
assert_not_includes post.posts.has_many, reply
end
test 'se puede cambiar la relación' do
reply = @site.posts.create(layout: :post, title: SecureRandom.hex)
post1 = @site.posts.create(layout: :post, title: SecureRandom.hex, posts: [reply.uuid.value])
post2 = @site.posts.create(layout: :post, title: SecureRandom.hex)
reply.in_reply_to.value = post2.uuid.value
reply.save
assert_not_equal post1, reply.in_reply_to.belongs_to
assert_equal post1, reply.in_reply_to.belonged_to
assert_not_includes post1.posts.has_many, reply
assert_equal post2, reply.in_reply_to.belongs_to
assert_includes post2.posts.has_many, reply
end
end