如何测试我正在验证一种关系在 RSpec 中至少有一个条目?

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

我有一个 has_many 关系,其中应该至少有一个条目。如果没有任何条目,则无效。

如何在 RSpec 中测试该验证?

我得到的最接近的是 it { should validate_length_of(:fees).is_at_least(1) },但它是为字符串设计的,不会工作。

假设您有一个 class 实例,例如 described_class_object,您可以这样做:

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

如果您有 has_many 图书用户关系。 用户设置为用户对象

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

期待在rspec

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