Shoulda-matchers: [Question] Working with belongs_to :relation, required: true

Created on 11 Dec 2015  Â·  6Comments  Â·  Source: thoughtbot/shoulda-matchers

If you have something like

class Group < ActiveRecord::Base
  belongs_to :manager, required: true
end

Currently, what I can do on my specs is:

it { is_expected.to belong_to(:manager) }
it { is_expected.to validate_presence_of(:manager) }

Which does cover it for me, but I'm curious as to ideas on having something in the likes of:

it { is_expected.to belong_to(:manager).with_required(true) }

If it's in the docs, I apologize, I couldn't find it

Feature Request 🛤 Rails 5

Most helpful comment

Just FYI, try .with_message(:required) to shorten it a little bit:)

All 6 comments

I believe this may be a newer option that we haven't added yet (I haven't heard of it).

That would be a good idea to add (although I'd have the qualifier be required(true) instead of with_required(true)).

In rails 5 required: true will be default option for belongs_to, so it makes sense to make it default in shoulda-matchers too.
See also #870.

I'm using Rails 5.0.0.beta3 with RSpec 3.5.0.beta2 and shoulda-matchers 3.1.1

Consider:

class User < ApplicationRecord
  has_many :changesets, inverse_of: :user, dependent: :restrict_with_error
end

class Changeset < ApplicationRecord
  belongs_to :user, inverse_of: :changesets
end

RSpec.describe Changeset, type: :model do
  subject { create :changeset }

  it { is_expected.to belong_to(:user).inverse_of(:changesets) }
  it { is_expected.to validate_presence_of :user }
end

Rails changed the "required" belongs_to validation message.
The it { is_expected.to validate_presence_of :user } assertion fails:

  1) Changeset should validate that :user cannot be empty/falsy
     Failure/Error: it { is_expected.to validate_presence_of :user }

       Changeset did not properly validate that :user cannot be empty/falsy.
         After setting :user to ‹nil›, the matcher expected the Changeset to be
         invalid and to produce the validation error "can't be blank" on :user.
         The record was indeed invalid, but it produced these validation errors
         instead:

         * user: ["must exist"]

Specifying the message fixes it for now:

it { is_expected.to validate_presence_of(:user).with_message('must exist') }

Just FYI, try .with_message(:required) to shorten it a little bit:)

@mcmire @stephanngamedev Isn't that issue resolved by now?

@robbl-as Yup! Sorry. Not sure why this issue wasn't closed automatically. This will be in the next release, or if you're feeling adventurous, you can point to master.

Was this page helpful?
0 / 5 - 0 ratings