rspec-railsruby-on-rails-5polymorphic-associations

How do I test a model with a polymorphic belongs_to association in isolation?


Up front, I'm using:

I've set up a mountable Rails engine with a polymorphic model that I want to use in other engines. The model class looks like this:

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

In my specs I'd like to make sure that I have a valid model, however, within the engine I have no other model that is associated with Geo::Location.

How can I set up a dummy class for testing validity (belongs_to require presence) or what are good testing strategies that you have used?


Solution

  • You can use the Shoulda gem and it's belong_to matcher (https://github.com/thoughtbot/shoulda-matchers#activerecord-matchers). Something like:

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