我正在尝试使用 shoulda 匹配器测试 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 匹配器代码:
# video_spec.rb
it { should have_one(:container).through(:contents) }
我得到的错误是:
undefined method `klass' for nil:NilClass
谁能告诉我为什么会收到此错误以及如何正确测试此关联?
最佳答案
假设这就是您规范文件中的全部代码(如果您只是发布了精简版本,我深表歉意),那么您需要将 shoulda 匹配器嵌套在 describe
下Video
类的 block :
describe Video do
it { should have_one(:container).through(:contents) }
end
您收到的错误表明正在测试的主题为nil
。通过将规范嵌套在 Video
类的 describe
block 中,测试的主题隐式是 Video
类。
在 documentation in the source code 处达到峰值,其中有很多很好的例子。
关于ruby-on-rails - Rails 和 Rspec - 具有一通多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25354912/