簡體   English   中英

Rails和Rspec-具有多態性

[英]Rails and Rspec - Has One Through Polymorphic

我正在嘗試使用Shoulda Matchers在rails中測試has_one:through關系。

我的關系結構看起來像這樣(這是反向多態關聯-https://gist.github.com/runemadsen/1242485

class Container < ActiveRecord::Base
  has_many :contents
  has_many :videos, through: :contents, source: :item, source_type: "Video"
end

class Content < ActiveRecord::Base
  belongs_to :container, dependent: :destroy
  belongs_to :item, polymorphic: true, dependent: :destroy
end

class Video < ActiveRecord::Base
  has_one :content, as: :item
  has_one :container, through: :contents
end

這是我在Rspec中的Shoulda Matcher代碼:

# video_spec.rb
it { should have_one(:container).through(:contents) }

我得到的錯誤是:

undefined method `klass' for nil:NilClass

誰能告訴我為什么我收到此錯誤以及如何正確測試此關聯?

假設這是您的規范文件中的所有代碼(如果您只是發布簡化版本,我深表歉意),那么您需要將Shoulda Matcher嵌套在Video類的describe塊下:

describe Video do
  it { should have_one(:container).through(:contents) }
end

您得到的錯誤表明被測對象為nil 通過將規范嵌套在Video類的describe塊中,被測對象隱式為Video類。

充分利用源代碼中的文檔 ,其中包含大量的示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM