RonLugge
RonLugge

Reputation: 5174

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.

Upvotes: 0

Views: 220

Answers (2)

nitishmadhukar
nitishmadhukar

Reputation: 236

If you have a user has_many books relationship. User is set to a user object

it { user.books.count.should be >= 1 }

with expect in rspec

it { expect(user.books.count).to be >= 1 }

Upvotes: 0

mr_sudaca
mr_sudaca

Reputation: 1176

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

Upvotes: 1

Related Questions