使用alias_attribute测试关联

Car*_*rds 5 activerecord alias rspec ruby-on-rails

我打算为我的几个模型关联使用别名属性.注意:我完全知道我也可以通过以下方式对此关联进行别名:

belongs_to :type, class_name: "AlbumType"
Run Code Online (Sandbox Code Playgroud)

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

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

class AlbumType < ApplicationRecord
  has_many :albums
end
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.我现在想在我的专辑规范中测试别名关联.看起来传统的belongs_toshoulda-matcher并不足以识别该类型album_type,即使在指定类名后也是如此.我当然不会对编写传统的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
Run Code Online (Sandbox Code Playgroud)

Ale*_*lim 3

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

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

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

build_association(attributes = {})
create_association(attributes = {})
create_association!(attributes = {})
Run Code Online (Sandbox Code Playgroud)

根据您的示例,使用alias_attribute不会给您带来好处album.build_album_type,而这是其他贡献者可能愿意依赖的东西,因为他们希望这是默认行为。

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