如何单独测试具有多态belongs_to关联的模型?

时间:2016-11-15 16:36:38

标签: rspec-rails ruby-on-rails-5 polymorphic-associations

预先,我使用:

  • Ruby 2.3.1
  • Rails 5
  • rspec-rails 3.5

我已经设置了一个可安装的Rails引擎,其中包含我想在其他引擎中使用的多态模型。模型类如下所示:

module Geo
  class Location < ApplicationRecord
    belongs_to :locatable, polymorphic: true
  end
end

在我的规格中,我想确保我有一个有效的模型,但是,在引擎中我没有其他与Geo::Location相关联的模型。

如何设置虚拟类来测试有效性(belongs_to需要存在)或您使用过的优秀测试策略?

1 个答案:

答案 0 :(得分:0)

您可以使用Shoulda gem及其belong_to匹配器(https://github.com/thoughtbot/shoulda-matchers#activerecord-matchers)。类似的东西:

it "has a polymorphic relationship" do
  expect(subject).to belong_to(:locatable)
end
相关问题