测试与 alias_attribute 的关联

Testing an association with an alias_attribute

我计划为我的几个模型关联使用别名属性。 注意:我完全知道我也可以通过以下方式别名此关联:

belongs_to :type, class_name: "AlbumType"

但想进一步探索 alias_attribute 方法。考虑到这一点,我有一个 Album 属于 AlbumType.

class Album < ApplicationRecord
  alias_attribute :type, :album_type
  belongs_to :album_type
end

class AlbumType < ApplicationRecord
  has_many :albums
end

到目前为止一切顺利。我现在想在我的专辑规范中测试别名关联。似乎传统的 belongs_to shoulda-matcher 不够聪明,无法识别 typealbum_type,即使在指定 class 名称之后。我当然不反对编写传统的 RSpec 测试,但不确定在这种情况下如何编写。任何帮助将不胜感激。

RSpec.describe Album, type: :model do
  describe "ActiveRecord associations" do
    it { should belong_to(:album_type) }

    context "alias attributes" do
      it { should belong_to(:type).class_name("AlbumType") }
    end
  end
end

我不建议为此目的使用 alias_attribute。据我所知,shoulda 使用 ActiveRecord::Reflection 来调查关联。 alias_attribute 唯一做的就是创建方法,通过 getter、setter 和 '?' 将消息从目标代理到源。方法。它显然是为了使用 ActiveRecord 属性而不是通用方法。

这样做的结果是 alias_attribute 不会将这些目标注册为 ActiveRecord 关联,并且 shoulda 的当前实现将无法捕获它们。

该模式也有副作用。您可能知道,当您创建关联时,ActiveRecord 还会创建辅助方法以使您的生活更轻松。例如,belongs_to 还会创建:

build_association(attributes = {})
create_association(attributes = {})
create_association!(attributes = {})

以你的例子为例,使用 alias_attribute 不会给你 album.build_album_type 而这是其他贡献者可能愿意依赖的东西,因为他们希望这是默认行为。

处理此问题的最佳方法正是您告诉过您不想做的事情,即使用 belongs_to 方法以您真正想要的名称创建关联。