ruby-on-railsrspecshoulda-matchers

rspec shoulda matchers is expected to belong to polymorphic


I am trying to test my polymorphic association but I cant seem to get it to pass

Model:

class Foo < ApplicationRecord
  belongs_to :bar, polymorphic: true, optional: true
end

Now my test looks like

RSpec.describe Foo, type: :model do
  subject { build(:foo) }
  it { is_expected.to belong_to(:bar) }
end

The error that I am getting

Foo
  is expected to belong to bar required: true (FAILED - 1)

Failures:

>   1) Foo is expected to belong to bar required: true
>      Failure/Error: it { is_expected.to belong_to(:bar) }
>        Expected Foo to have a belongs_to association called bar (and for the record to fail validation if :bar is unset; i.e., either the
> association should have been defined with `required: true`, or there
> should be a presence validation on :bar)
>      /# ./spec/models/foo_spec.rb:4:in `block (2 levels) in <top (required)>'

Now this association can be a nil value


Solution

  • The issue seems to be:

    and for the record to fail validation if :bar is unset;

    Since, you have optional: true - this part is not satisfied.

    It looks like shoulda assumes a relation should be required, unless you tell it otherwise.

    Try modifying this matcher like so

    it { is_expected.to belong_to(:bar).optional }
    

    https://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_record/association_matcher.rb#L304:L321