Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby / RSpec - Expect not to include any of

Tags:

ruby

rspec

I have the following spec:

describe 'active' do
  it 'does not include inactive or deleted records' do
    inactive_record= create(:record, :inactive)
    deleted_record= create(:record, :deleted)
    expect(described_class.active).not_to include inactive_record
    expect(described_class.active).not_to include deleted_record
  end
end

This is OK when there are two tests, but when I have 10 different statuses I need to check, I'd need to write out ten different expect lines. I can do something like this:

[records_not_to_be_included].each { |record| expect(described_class.active).not_to include record }

But would like to be able to do something like:

expect(described_class.active).not_to include_any_of [records_not_to_be_included]

Is this possible with RSpec?

like image 381
Mark Avatar asked Oct 15 '25 16:10

Mark


1 Answers

As you can see, from the docs:

# Passes if actual includes expected. This works for
# collections and Strings. You can also pass in multiple args
# and it will only pass if all args are found in collection.
#
# @example
#   expect([1,2,3]).to      include(3)
#   expect([1,2,3]).to      include(2,3)
#   expect([1,2,3]).not_to  include(4)
#   expect("spread").to     include("read")
#   expect("spread").not_to include("red")
#   expect(:a => 1, :b => 2).to include(:b => 2, :a => 1)
#   expect(:a => 1, :b => 2).not_to include(:a => 2)
#   ...
def include(*expected)
  BuiltIn::Include.new(*expected)
end

include accepts one or more elements, so you can try with:

expect(described_class.active).not_to include(inactive_record, deleted_record)
like image 149
Sebastian Palma Avatar answered Oct 18 '25 06:10

Sebastian Palma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!