Search code examples
ruby-on-railsrspecrspec-rails

How to test that I am validating that a relationship has at least one entry in RSpec?


I have a has_many relationship that should always have at least one entry in it. If there aren't any entries, it's invalid.

How do I test that validation in RSpec?

Closest I've gotten is it { should validate_length_of(:fees).is_at_least(1) }, but that's intended for strings and won't work.


Solution

  • assuming that you have an instance of your class like described_class_object, you can do:

    context 'when there are no fees' do
      it 'is not valid' do
        described_class_object = described_class.build(...some params...)
        described_class_object.fees = []
        expect(described_class_object).to_not be_valid
      end
    end