【发布时间】:2016-10-03 01:32:12
【问题描述】:
我计划为我的几个模型关联使用别名属性。 注意:我完全知道我也可以通过以下方式别名此关联:
belongs_to :type, class_name: "AlbumType"
但想进一步探索alias_attribute 方法。考虑到这一点,我有一个属于AlbumType 的Album。
class Album < ApplicationRecord
alias_attribute :type, :album_type
belongs_to :album_type
end
class AlbumType < ApplicationRecord
has_many :albums
end
到目前为止一切顺利。我现在想在我的专辑规范中测试别名关联。即使在指定类名之后,传统的belongs_to shoulda-matcher 似乎也不够聪明,无法识别 type 是 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
【问题讨论】:
标签: ruby-on-rails activerecord rspec alias