[英]Testing an association with an alias_attribute
我打算為我的幾個模型關聯使用別名屬性。 注意:我完全知道我也可以通過以下方式對此關聯進行別名 :
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似乎不夠聰明,即使在指定類名后也無法識別該類型是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
我不建議為此目的使用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
方法以您真正想要的名稱創建關聯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.