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

2

5

Up front, I'm using:

  • Ruby 2.3.1
  • Rails 5
  • rspec-rails 3.5

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?

Otiliaotina answered 15/11, 2016 at 16:36 Comment(0)
C
10

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
Calumnious answered 30/8, 2017 at 16:27 Comment(0)
E
3

Another way to write this is:

describe YourClass do
  it { is_expected.to belong_to(:locatable) }
end
Eponymy answered 28/9, 2022 at 21:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.