如何单独测试具有多态 belongs_to 关联的模型?
How do I test a model with a polymorphic belongs_to association in isolation?
首先,我使用的是:
- Ruby 2.3.1
- Rails 5
- rspec-rails 3.5
我已经设置了一个可安装的 Rails 引擎,它具有我想在其他引擎中使用的多态模型。模型 class 看起来像这样:
module Geo
class Location < ApplicationRecord
belongs_to :locatable, polymorphic: true
end
end
在我的规范中,我想确保我有一个有效的模型,但是,在引擎中我没有其他模型与 Geo::Location
关联。
我如何设置一个虚拟 class 来测试有效性(belongs_to
需要存在)或者你使用过哪些好的测试策略?
您可以使用Shoulda gem and it's belong_to
matcher (https://github.com/thoughtbot/shoulda-matchers#activerecord-matchers)。类似于:
it "has a polymorphic relationship" do
expect(subject).to belong_to(:locatable)
end
首先,我使用的是:
- Ruby 2.3.1
- Rails 5
- rspec-rails 3.5
我已经设置了一个可安装的 Rails 引擎,它具有我想在其他引擎中使用的多态模型。模型 class 看起来像这样:
module Geo
class Location < ApplicationRecord
belongs_to :locatable, polymorphic: true
end
end
在我的规范中,我想确保我有一个有效的模型,但是,在引擎中我没有其他模型与 Geo::Location
关联。
我如何设置一个虚拟 class 来测试有效性(belongs_to
需要存在)或者你使用过哪些好的测试策略?
您可以使用Shoulda gem and it's belong_to
matcher (https://github.com/thoughtbot/shoulda-matchers#activerecord-matchers)。类似于:
it "has a polymorphic relationship" do
expect(subject).to belong_to(:locatable)
end